【问题标题】:React Native - get refs of custom components in listview from renderRowReact Native - 从 renderRow 获取列表视图中自定义组件的引用
【发布时间】:2016-07-08 02:36:13
【问题描述】:

我有一个 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} />
   );
}

【问题讨论】:

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


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      相关资源
      最近更新 更多