2017-07-14 62 views
4

我希望對使用React參考調用子函數有一定的瞭解。我有一個父組件,它是一個帶有幾個按鈕的工具欄,在子組件中,我可以訪問庫的導出功能。我想通過父組件中的按鈕單擊來調用此導出函數。目前我使用的反應裁判來實現:使用React參考調用子函數的最佳實踐

Parent.js [參考]

class Parent extends React.Component { 

    onExportClick =() => { 
    this.childRef.export(); 
    } 

    render() { 
    return (
     <div> 
     <button onClick={this.onExportClick} />Export</button> 
     <Child ref={(node) => this.childRef = node;} /> 
     </div> 
    ) 
    } 
} 

Child.js [參考]

class Child extends React.Component { 

    export() { 
    this.api.exportData(); 
    } 

    render() { 
    <ExternalLibComponent 
     api={(api) => this.api = api} 
    /> 
    } 
} 

這個解決方案工作正常,但如果這是最佳做法,我已經看過lotdisagreement。 React的doc關於refs說我們應該「避免使用refs來處理任何可以聲明的事情」。在discussion post對於一個類似的問題,React團隊的Ben Alpert說「refs是專門爲這個用例設計的」,但通常你應該試着通過傳遞一個prop來聲明它。

這是我會怎麼做聲明這一點沒有ref

Parent.js [聲明]

class Parent extends React.Component { 

    onExportClick =() => { 
    // Set to trigger props change in child 
    this.setState({ 
     shouldExport: true, 
    }); 

    // Toggle back to false to ensure child doesn't keep 
    // calling export on subsequent props changes 
    // ?? this doesn't seem right 
    this.setState({ 
     shouldExport: false, 
    }); 
    } 

    render() { 
    return (
     <div> 
     <button onClick={this.onExportClick} />Export</button> 
     <Child shouldExport={this.state.shouldExport}/> 
     </div> 
    ) 
    } 
} 

Child.js [聲明]

class Child extends React.Component { 

    componentWillReceiveProps(nextProps) { 
    if (nextProps.shouldExport) { 
     this.export(); 
    } 
    } 

    export() { 
    this.api.exportData(); 
    } 

    render() { 
    <ExternalLibComponent 
     api={(api) => this.api = api} 
    /> 
    } 
} 

雖然裁判被認爲是這個問題的「逃生艙」,這個說明性的解決方案似乎有點冒險,並沒有比使用文獻更好。我應該繼續使用參考來解決這個問題嗎?或者我應該採用有點冒險的陳述方式?

回答

1

你並不需要設置shouldExportfalse,你可以代替檢測的變化:

componentWillReceiveProps(nextProps) { 
    if (nextProps.shouldExport !== this.props.shouldExport) { 
     this.export(); 
    } 
} 

然後shouldExport的每一個切換會導致只有一個出口。然而,這看起來奇怪,我會使用一個號碼,我會增加:

componentWillReceiveProps(nextProps) { 
    if (nextProps.exportCount > this.props.exportCount) { 
     this.export(); 
    } 
} 
1

我跑進多次同樣的問題,現在,因爲該陣營隊不鼓勵它,我將使用這個道具方法用於後期開發,但問題是有時候你想要返回一個值給父組件,有時你需要檢查孩子的狀態來決定是否觸發一個事件,因此refs方法將永遠是我最後的避風港,我建議你也這樣做

+0

謝謝。現在我清楚,答案是「取決於」。這不是一個黑色和白色的情況。 – Alex