這篇文章將為大家詳細講解有關React組件通信的案例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
最近閑來無事自學React框架,自學過程中所有的問題經驗都會在此記錄,希望可以幫助到學習React框架的同學,廢話不多說上代碼。
首先是父傳子:
import React, { Component } from 'react'; import Com1 from './componments/com1' class App extends Component { constructor(props){ super(props) this.state = { arr: [{ "userName": "fangMing", "text": "123333", "result": true }, { "userName": "zhangSan", "text": "345555", "result": false }, { "userName": "liSi", "text": "567777", "result": true }, { "userName": "wangWu", "text": "789999", "result": true },] }; this.foo = "我來自父組件" //這個也是父傳子方法,可能初學者有點迷,剛開始我也用來和arr = {this.state.arr}做區分 }; render() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> </header> <Com1 age="大衛" arr={this.state.arr} fn={this.foo}/> </div> ); } } export default App;
子組件:
import React, { Component } from 'react'; class Ele extends Component{ constructor(props){ super(props) }; render(){ return ( <div> <h2>Hello, {this.props.age}</h2> <p>{this.props.fn}</p> <ul> { this.props.arr.map(item => { //這個地方通過this.props.arr接收到父組件傳過來的arr,然后在{}里面進行js的循環 return ( <li key={item.userName}> {item.userName} 評論是:{item.text} </li> ) }) } </ul> </div> ); }; } export default Ele;
結果顯示:
以上是父傳子的方法,主要還是使用props傳值,下面看看子傳父.
子傳父:
首先是子組件:
import React, { Component } from 'react'; class Ele extends Component{ constructor(props){ super(props); this.state = ({ childText: "我來自子組件" }) }; clickFun(text) { //定義觸發的方法 this.props.pfn(text)//這個地方把值傳遞給了props的事件當中 } render(){ return ( <div> {/* 通過事件進行傳值,如果想得到event,可以在參數最后加一個event, 這個地方還是要強調,this,this,this */} <button onClick={this.clickFun.bind(this, this.state.childText)}> 傳值 </button> </div> ); }; } export default Ele;
父組件:
import React, { Component } from 'react'; import Com1 from './componments/com1' class App extends Component { constructor(props){ super(props) this.state = { parentText: "現在是父組件", }; fn(data) { this.setState({ parentText: data //把父組件中的parentText替換為子組件傳遞的值 },() =>{ console.log(this.state.parentText);//setState是異步操作,但是我們可以在它的回調函數里面進行操作 }); }; render() { return ( <div className="App"> <Com1 pfn={this.fn.bind(this)}/> {/*通過綁定事件進行值的運算,這個地方一定要記得.bind(this),不然會報錯,切記切記,因為通過事件傳遞的時候this的指向已經改變 */} <p>text is {this.state.parentText}</p> </div> ); } } export default App;
關于React組件通信的案例分析就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。