React Native-从renderRow获取ListView中自定义组件的引用 [英] React Native - get refs of custom components in listview from renderRow

查看:257
本文介绍了React Native-从renderRow获取ListView中自定义组件的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

该类具有以下功能:

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

推荐答案

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

First, you have a syntactical error in your code:

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

第二,当您调用this.refs.listView.refs时,ref回调函数必须将ref实际存储在要引用的位置.您期望这个价值来自何处? React不允许这种神奇的子引用存储,这完全是手动的.您可以在回调中获得对该特定组件的引用,您必须弄清楚该如何处理.

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

这篇关于React Native-从renderRow获取ListView中自定义组件的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆