本文介紹了React 子組件向父組件傳值的方法,分享給大家
子組件需要控制自己的 state, 然后告訴父組件自己的state,通過props調(diào)用父組件中用來控制state的函數(shù),在父組件中展示子組件的state變化。
/***實(shí)現(xiàn)在輸入框輸入郵箱時(shí),在div中即時(shí)顯示輸入內(nèi)容***/<body> <div id="test"></div></body>//子組件var Child = React.createClass({ render: function(){ return ( <div> 郵箱:<input onChange={this.props.handleEmail}/> </div> ) }});//父組件var Parent = React.createClass({ getInitialState: function(){ return { email: '' } }, handleEmail: function(event){ this.setState({email: event.target.value}); }, render: function(){ return ( <div> <div>郵箱:{this.state.email}</div> <Child name="email" handleEmail={this.handleEmail.bind(this)}/> </div> ) }});React.render( <Parent />, document.getElementById('test'));原理:
依賴 props 來傳遞事件的引用,并通過回調(diào)的方式來實(shí)現(xiàn)的,這樣實(shí)現(xiàn)不是特別好,但在沒有任何工具的情況下是一種簡(jiǎn)單的實(shí)現(xiàn)方式。
分析:
React中當(dāng)state發(fā)生改變時(shí),組件才會(huì)update。在父組件中設(shè)定state的初始值以及處理該state的函數(shù),同時(shí)將函數(shù)名通過以props屬性值的形式傳入子組件,子組件通過調(diào)用父組件的函數(shù),進(jìn)而引起state變化,達(dá)到在父組件中展示子組件產(chǎn)生的變化。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持錯(cuò)新站長(zhǎng)站。
新聞熱點(diǎn)
疑難解答
圖片精選