2016-07-08 44 views
3

我有一個ListView,並試圖訪問我在renderRow中編寫的自定義組件的ref。我需要對自定義組件進行一些直接操作,所以我需要獲取這些參數的參考。React Native - 從renderRow獲取listview中的自定義組件的refs

好像其他人也遇到過這個問題。我試着按照React Native: Refs in ListViewhttps://github.com/facebook/react-native/issues/897的建議,但他們似乎不適合我。建議使用回調引用方法。但是,當我嘗試在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} /> 
    ); 
} 

回答

2

首先,你必須在你的代碼中的語法錯誤:

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

其次,裁判回調函數具有實際存儲裁判當您致電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} /> 
    ); 
}, 
... 
相關問題