這篇文章主要為大家展示了“如何實現React組件之間的通信”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“如何實現React組件之間的通信”這篇文章吧。
1.定義兩個子組件child-1和child-2
//child-1 子組件-1為輸入框 class Input extends React.Component{ constructor(...args){ super(...args); } render(){ return <input type="text"/> } } //child-2 子組-2為顯示框 class Show extends React.Component{ constructor(...args){ super(...args); } render(){ return <p></p> } }
2.定義父組件Parent并且將兩個子組件插入到父組件中
class Parent extends React.Component{ constructor(...args){ super(...args); } render(){ return( <div> <Input}/> <Show/> </div> ); } }
現在的任務是在組件1總輸入一些文字,同時在組件2中同時顯示出來。
分析:要讓組件2與組件1同步,就讓組件1和2都去綁定父組件的狀態。也就是說讓兩個組件受控。數據的走向是,組件1將自身的數據提升到父層,并且保存在父層的狀態中。父層中的數據通過組件2中的props屬性傳遞到組件2中,并在視圖層進行綁定。
第一步先綁定<Show/>組件
//在父層中的constructor中定義狀態為一個空的message,this.state = {message:''} class Parent extends React.Component{ constructor(...args){ super(...args); this.state = { message:'' }
然后在父組件中的<Show/>改為
<Show onShow={this.state.message}/>
接著來我們進入到<Show/>組件中,給其內容綁定這個穿件來的onShow屬性。<Show/>組件變為
class Show extends React.Component{ constructor(...args){ super(...args); } render(){ return <p>{this.props.onShow}</p> }
這樣組件2顯示層的數據已經綁定好了,接下來我們只要改變父親層狀態中的message的內容就可以使綁定的顯示層的內容跟著一起變化
將輸入層的狀態(數據)提升到父親組件中.下面是改寫后的組件1
class Input extends React.Component{ constructor(...args){ super(...args); } //將輸入的內容更新到自身組件的狀態中,并且將改變后的狀態作為參數傳遞給該組件的一個自定義屬性onInp() fn(ev){ this.props.onInp(ev.target.value); } render(){ //用onInput(注意react中采用駝峰寫法和原生的略有不同)綁定fn()函數 return <input type="text" onInput={this.fn.bind(this)} value={this.props.content}/> } }
看到這里可能會有一個問題:onInp()和content沒有啊?不要急,接著看
接著改寫父組件中的輸入層子組件1,
class Parent extends React.Component{ constructor(...args){ super(...args); this.state = { message:'' }; } //傳進的text是其提升上來的狀態,然后再更新父組件的狀態 fn(text){ this.setState({ message:text }) } render(){ return( <div> /* onInp就出現在這里,并綁定一個函數, 并且有一個content將父組件的狀態同步到子組件中 */ <Input onInp={this.fn.bind(this)} content={this.state.message}/> <Show onShow={this.state.message}/> </div> ); } }
寫完的代碼是這樣的
// 父組 class Parent extends React.Component{ constructor(...args){ super(...args); this.state = { message:'' }; } onInp(text){ this.setState({ message:text }) } render(){ return( <div> <Input onInp={this.onInp.bind(this)} content={this.state.message}/> <Show onShow={this.state.message}/> </div> ); } } //child-1 class Input extends React.Component{ constructor(...args){ super(...args); } fn(ev){ this.props.onInp(ev.target.value); } render(){ return <input type="text" onInput={this.fn.bind(this)} value={this.props.content}/> } } //child-2 class Show extends React.Component{ constructor(...args){ super(...args); } render(){ return <p>{this.props.onShow}</p> } } //最后渲染出 ReactDOM.render( <Parent/>, document.getElementById('app') );
以上是“如何實現React組件之間的通信”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。