React之组件通信
? 組件通信無(wú)外乎,下面這三種父子組件,子父組件,平行組件(也叫兄弟組件)間的數(shù)據(jù)傳輸。下面我們來(lái)分別說(shuō)一下:
父子組件:
var Demo=React.createClass({getInitialState:function(){return{res:''}},tap:function(e){var str=e.target.value;this.setState({res:str})},render:function(){return(<div><h1>父組件</h1><input type="text" onChange={this.tap}/><Child name={this.state.res}/></div> )} }) var Child=React.createClass({render:function(){console.log(this.props)return(<div><h1>子組件</h1><p>{this.props.name}</p></div> )} }) ReactDOM.render(<Demo/>,document.getElementById('out'))這里我們通過(guò)設(shè)置默認(rèn)狀態(tài),添加onchange事件,并把狀態(tài)以默認(rèn)屬性的形式給子組件,然后通過(guò)this.props來(lái)獲取。
說(shuō)完了父子組件,那么子組件如何傳遞到父組件呢?
<script type="text/babel">var Demo=React.createClass({getInitialState:function(){return{res:''}},render:function(){var _this=this;return(<div><h1>父組件</h1><p>{this.state.res}</p><Child name={function(s){_this.setState({res:s})}}/></div> )} }) var Child=React.createClass({tap:function(e){var str=e.target.value;console.log(str) // this.props.name==function // this.props.name(a)==function(s) // a==sthis.props.name(str) // str==s },render:function(){console.log(this.props)return(<div><h1>子組件</h1><input type="text" onChange={this.tap}/> </div> )} }) ReactDOM.render(<Demo/>,document.getElementById('out'))</script>【子組件】控制自己的 state 然后告訴【父組件】的點(diǎn)擊狀態(tài),然后在【父組件】中展示出來(lái)。
----------------------------------------------------------------------------------------------------------------------------------------------------
同級(jí)組件間的通訊復(fù)雜點(diǎn),不過(guò)這里可以說(shuō)點(diǎn)思路,假如這兩個(gè)組件擁有相同的父組件可以將父組件作為橋梁,一個(gè)組件先傳遞給父組件,然后父組件再傳遞給兄弟組件。
另外還可以使用觀察著模式,還有redux。這兩個(gè)我還沒(méi)完全理解,日后再說(shuō)。
轉(zhuǎn)載于:https://www.cnblogs.com/ztl0918/p/6920963.html
總結(jié)
以上是生活随笔為你收集整理的React之组件通信的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 使用FindBugs-IDEA插件找到代
- 下一篇: 向文件中追加内容