React Native - 从renderRow

时间:2016-07-08 02:36:13

标签: react-native ref react-native-listview

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

似乎其他人也遇到过这个问题。我已尝试按照React Native: Refs in ListViewhttps://github.com/facebook/react-native/issues/897中的建议进行操作,但它们似乎并不适用于我。我已经尝试使用建议的回调ref方法。但是,当我尝试在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} />
   );
}

1 个答案:

答案 0 :(得分:3)

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

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

其次,当你调用this.refs.listView.refs时,ref回调函数必须将ref实际存储在某个地方。你认为这个价值来自哪里? 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} />
   );
},
...