【问题标题】:create a unique ref for each element while renderItem() in a SectionList/ FlatList react native为每个元素创建一个唯一的引用,而 SectionList/FlatList 中的 renderItem() 反应原生
【发布时间】:2017-09-17 15:41:58
【问题描述】:

这是下面的一个基本示例:

 renderItem: ({ item }) =>          


            <SwipeRow

              ref={(SwipeRow) => { refSwipeRow = SwipeRow }}  >

              <TouchableOpacity 
                onPress={() => {
                    refSwipeRow.closeRow()
                }
              </TouchableOpacity>
            </SwipeRow>

虽然 onPress refSwipeRow.closeRow() 被调用,但它只适用于最后一个索引,技术上它是正确的,因为在渲染时 ref 被覆盖并且在end 它只保存最后一个索引引用。

如何为每个元素创建一个唯一的 ref。

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    在渲染FlatList/SectionList 时,您应该为每个渲染的项目添加一个唯一的键道具。您可以使用 keyExtractor 属性为 FlatList and SectionList 实现此目的。你可以阅读更多here

    对于您的问题,您可以将 refs 设置为具有唯一 ID 的单个对象。然后onPress 触发,您可以使用该唯一值来关闭行。

    举例

    renderItem: ({ item }) => (          
                  <SwipeRow
                    ref={(SwipeRow) => { this.rowRefs[item.id] = SwipeRow; }}  >
                      <TouchableOpacity 
                        onPress={() => {
                          this.rowRefs[item.id].closeRow();
                        }
                      </TouchableOpacity>
                  </SwipeRow>
                )
    

    更新 要使用this.rowRefs[item.id],您应该在组件的constructor 中将其声明为像这样的空对象,

    constructor(props) {
      super(props);
      this.rowRefs = {};
    }
    

    【讨论】:

    • 非常感谢您的回复,是否必须使用 keyExtractor?我不能在 item.id 中使用我自己的唯一键,它直接来自 API。
    • 就像我在答案中所说,你应该添加,但这不是强制性的。您可以为密钥使用任何值。阅读文档并查找示例。
    • 它给了我一个错误cannot set property '1' undefine. :(
    • 请用您尝试过的内容和遇到的完整错误更新您的问题。
    • @SandeepKumar 我更新了我的答案。请检查是否有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    • 2014-03-06
    • 2015-06-14
    相关资源
    最近更新 更多