【问题标题】:render four button on each item in flatlist programmatically react native在平面列表中的每个项目上呈现四个按钮以编程方式反应本机
【发布时间】:2020-01-21 12:19:31
【问题描述】:

我正在从 API 获取数据,数据以下面的形式出现

data : [
        {
          source1: { number: 1,title: '', content: ''},
          source2: { number: 2, title: '',content: ''},
          source3: { number: 4,  title: '',content: '' },
          id: '1',
          title: '',
        },
        {
          source1: { number: 1,title: '', content: ''},
          source2: { number: 2, title: '',content: ''},
          source3: { number: 4,  title: '',content: '' },
          id: '2',
          title: '',
        }
      ]

我想在 Flatlist 上展示我想要的东西

有四个按钮。

当点击一个时,文本将被更改,按钮样式也将被更新。按钮标题和更改文本将来自 data -> soruce 1 (button 1) source2 (button 2) source3 (button 3) soruce 4 (button 4) 。单品

帮助我如何在 flatlist 上或通过 map() 实现每个渲染项?

谢谢

【问题讨论】:

  • 你真的需要为此使用 Flatlist 吗?对我来说看起来像是条件渲染
  • 还有为什么数据对象里面有3个source1键/
  • 如果你想通过 map() 给出答案,没问题。你可以
  • 抱歉我的错误,我已经更新了问题
  • @ThakurKarthik 。请立即查看更新后的问题

标签: javascript react-native state react-native-flatlist


【解决方案1】:

一种方法是在数据中维护一个 activeSource/activeItem,并根据 Touchable/Button 的源更改对其进行更新。这样可以很容易地维护每个项目的活动源。

data: [
 {source1:'',source2:'',source3:'',...,activeSource:'source1',id:1,Title:''},
 {source1:'',source2:'',source3:'',...,activeSource:'source1',id:2,Title:''},
 {source1:'',source2:'',source3:'',...,activeSource:'source1',id:3,Title:''},
 ...
]

从您在 renderItem 属性中获得的项目索引中更改 Touchable 中的 activeSource

renderItem=(({item,index})=>{...})

onChange 看起来像这样

changeSource = (source, itemIndex) => {
    this.setState(prevState => ({
      data: prevState.data.map((item, index) => {
        if (index !== itemIndex) return item;
        return {
          ...item,
          activeSource: source,
        };
      }),
    }));
  };

并将对应的源项渲染为

<Text>{item[item[activeSource]]}</Text

我正在附上一个博览会link

【讨论】:

  • 主动源到底是什么意思?
  • 由于您在数据数组的项目中有不同的来源,如 source1,source2,...,一个活动来源告诉应该显示哪个来源的数据,这是作为 item[item[activeSource] ]==>这里 item[activeSource] 将包含 source 的键。查看 expo 链接。
  • 你的代码很凝灰岩。我们仍在努力了解
  • 只需为状态中的每个数据项保留一个名为 activeSource 的变量。然后将此 activeSource 更新为可用的源,如 activeSource=source1/source2/... 并将与该源关联的数据呈现在renderItem 道具..我清楚了吗?
  • 非常感谢。你帮了我 。它就像魅力一样。也感谢那些提出我问题的人
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
  • 2021-11-23
  • 1970-01-01
  • 2017-06-04
相关资源
最近更新 更多