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

React Native - get refs of custom components in listview from renderRow

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

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

class有以下功能:

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} />
   );
},
...