最近閒來無事自學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;
子組件:git
import React, { Component } from 'react'; class Ele extends Component{ constructor(props){ super(props) }; render(){ return ( <div> <h1>Hello, {this.props.age}</h1> <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;
結果顯示:github
以上是父傳子的方法,主要仍是使用props傳值,下面看看子傳父.app
子傳父:
首先是子組件:框架
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;
以上是父子組件傳值的方法,有不對的地方還望指正
還有兄弟組件傳值還沒學到,兄弟組件傳值學到會更新上來
源碼地址:
https://github.com/Nick091608... 歡迎star函數