React Native - 从 renderRow 获取列表视图中自定义组件的引用

2024-02-22

我有一个 ListView,并尝试访问我在 renderRow 中编写的自定义组件的引用。我需要对自定义组件进行一些直接操作,因此我需要获取这些组件的引用。

似乎其他人也遇到过这个问题。我尝试遵循中的建议React Native:ListView 中的引用 https://stackoverflow.com/questions/36382431/react-native-refs-in-listview and https://github.com/facebook/react-native/issues/897 https://github.com/facebook/react-native/issues/897但它们似乎不适合我。我已尝试按照建议使用回调引用方法。但是,当我尝试在 componentDidMount 中打印 this.refs.listView.refs 时,它是空的而不是返回 customRef。如何从 renderRow 函数获取自定义组件的引用?谢谢

该类具有以下功能:

componentDidMount() {
   console.log(this.refs.listView.refs);
},

getRef() {
   return 'customRef';
},

renderRow(rowData) {
   return (
     <CustomComponent ref={(ref)=>this.getRef} key={rowData.key} />
   );
},

render() {
   return (
      <ListView
         ref={'listView'}
         dataSource={this.state.dataSource}
         renderRow={this.renderRow} />
   );
}

首先,您的代码中存在语法错误:

renderRow(rowData) {
   return (
     //                                     \/ Missing execution of getRef
     <CustomComponent ref={(ref)=>this.getRef} key={rowData.key} />
   );
},

其次,ref 回调函数必须实际将 ref 存储在调用时引用的地方this.refs.listView.refs。您期望这个值从哪里来? React 不允许这种神奇的子引用存储,它完全是手动的。您在回调中获得对此特定组件的引用,您必须弄清楚如何处理它。

constructor(props) {
    super(props);
    this.rowRefs = [];
    this.storeRowRef = this.storeRowRef.bind(this);
}
componentDidMount() {
    console.log(this.rowRefs.length);
}
storeRowRef(rowRef) {
    this.rowRefs.push(rowRef);
}
renderRow(rowData) {
   return (
     <CustomComponent ref={storeRowRef} key={rowData.key} />
   );
},
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React Native - 从 renderRow 获取列表视图中自定义组件的引用 的相关文章

随机推荐