为SectionList/FlatList中的renderItem()做出本机反应时,为每个元素创建一个唯一的引用

San*_*aha 1 reactjs react-native

这是一个基本的例子如下:

 renderItem: ({ item }) =>          


            <SwipeRow

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

              <TouchableOpacity 
                onPress={() => {
                    refSwipeRow.closeRow()
                }
              </TouchableOpacity>
            </SwipeRow>
Run Code Online (Sandbox Code Playgroud)

虽然onPress refSwipeRow.closeRow()被调用,但它只适用于最后一个索引,从技术上讲它是正确的,因为渲染ref的while 会被覆盖,最后它只保存最后一个索引引用.

如何为每个元素创建唯一的引用.

ben*_*nel 5

渲染时,FlatList/SectionList您应该为每个渲染项添加唯一的键道具.你可以用keyExtractorprop 来实现这一点FlatList and SectionList.你可以在这里阅读更多内容.

对于您的问题,您可以将refs设置为单个对象,并再次使用唯一ID.然后onPress解雇你可以使用该唯一值来关闭行.

例如

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

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

constructor(props) {
  super(props);
  this.rowRefs = {};
}
Run Code Online (Sandbox Code Playgroud)