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

孤者浪人 提交于 2020-01-14 19:09:48

问题


I have a ListView and am trying to access the refs of custom components I have written in the renderRow. I need to do some direct manipulation of the custom components so I need to get the refs of these.

It seems like other people have faced this issue too. I have tried following the recommendations in React Native: Refs in ListView and https://github.com/facebook/react-native/issues/897 but they don't seem to work for me. I have tried using the callback ref method as suggested. But, when I try printing out this.refs.listView.refs in componentDidMount, it is empty instead of returning customRef. How do I get the refs of the custom components from the renderRow function? Thank you

The class has the following functions:

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:


First, you have a syntactical error in your code:

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

Second, the ref callback function has to actually store the ref somewhere to be referenced when you call this.refs.listView.refs. Where do you expect this value to come from? React doesn't allow for this sort of magical child ref storage, it's totally manual. You get a ref to this particular component in your callback, you have to figure out what to do with it.

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


来源:https://stackoverflow.com/questions/38258143/react-native-get-refs-of-custom-components-in-listview-from-renderrow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!