在React.js 中,有多種方法從子元件傳遞資料給它的父級。雖然事件處理程序通常很方便,但了解最佳實踐和潛在陷阱也很重要。
為什麼我們不將整個子組件傳回
其他解決方案此問題可能建議透過事件處理程序將整個子組件傳遞回父組件。但是,通常不建議使用這種方法,因為:
更好的實現
相反,您應該利用父級已經擁有子級的 props的事實
孩子:
var Child = React.createClass({ render: function() { return <button onClick={this.props.onClick}>{this.props.text}</button>; }, });
家長(獨生子女):
var Parent = React.createClass({ getInitialState: function() { return { childText: "Click me! (parent prop)" }; }, render: function() { return <Child onClick={this.handleChildClick} text={this.state.childText} />; }, handleChildClick: function(event) { // Access the props passed to the child alert("The Child button text is: " + this.state.childText); // Access the click target alert("The Child HTML is: " + event.target.outerHTML); }, });
家長(多種的Children):
var Parent = React.createClass({ getInitialState: function() { return { childrenData: [ { childText: "Click me 1!", childNumber: 1 }, { childText: "Click me 2!", childNumber: 2 }, ], }; }, render: function() { const children = this.state.childrenData.map( (childData, childIndex) => { return ( <Child onClick={this.handleChildClick.bind(null, childData)} text={childData.childText} key={childIndex} // Added key for each child component /> ); } ); return <div>{children}</div>; }, handleChildClick: function(childData, event) { alert("The Child button data is: " + childData.childText + " - " + childData.childNumber); alert("The Child HTML is: " + event.target.outerHTML); }, });
在這些範例中,父元件可以存取子元件的props 和點擊目標,而不需要傳回整個子元件。
ES6 更新
對於 ES6文法,代碼如下圖所示:
孩子:
const Child = ({ onClick, text }) => ( <button onClick={onClick}>{text}</button> );
家長(獨生子女):
class Parent extends React.Component { state = { childText: "Click me! (parent prop)" }; handleChildClick = (event) => { alert("The Child button text is: " + this.state.childText); alert("The Child HTML is: " + event.target.outerHTML); }; render() { return <Child onClick={this.handleChildClick} text={this.state.childText} />; } }
class Parent extends React.Component { state = { childrenData: [ { childText: "Click me 1!", childNumber: 1 }, { childText: "Click me 2!", childNumber: 2 }, ], }; handleChildClick = (childData, event) => { alert("The Child button data is: " + childData.childText + " - " + childData.childNumber); alert("The Child HTML is: " + event.target.outerHTML); }; render() { const children = this.state.childrenData.map((childData, childIndex) => ( <Child key={childIndex} text={childData.childText} onClick={(e) => this.handleChildClick(childData, e)} /> )); return <div>{children}</div>; } }
以上是如何在 React.js 中將 Props 從子元件傳遞到父元件而不將整個子元件傳回?的詳細內容。更多資訊請關注PHP中文網其他相關文章!