我希望對使用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}
/>
}
}
這個解決方案工作正常,但如果這是最佳做法,我已經看過lot的disagreement。 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}
/>
}
}
雖然裁判被認爲是這個問題的「逃生艙」,這個說明性的解決方案似乎有點冒險,並沒有比使用文獻更好。我應該繼續使用參考來解決這個問題嗎?或者我應該採用有點冒險的陳述方式?
謝謝。現在我清楚,答案是「取決於」。這不是一個黑色和白色的情況。 – Alex