新增Child.js文件react
import React from 'react'; export default class Child extends React.Component{ render(){ return ( <div> <p>我是子組件</p> <p>{this.props.value}</p> </div> ) } }
修改Home2.js文import React from 'react';react-router
import {Link} from "react-router-dom"; import Child from './Child'; export default class Home2 extends React.Component{ constructor(props){ super(props); this.state = { father: 'father' } } changeRoute = () => { this.props.history.push('/twoPage'); }; render(){ return ( <div> <div> <p>我是Home2組件</p> <Link to="/onePage">點我跳轉到one頁面</Link><br/> <Link to="/twoPage/2">點我跳轉到two頁面</Link><br/> <Link to="/this">點我跳轉到this頁面</Link> <p onClick={this.changeRoute}>點我試試</p> </div> <div> <p>我是父組件</p>
<Child value={this.state.father} /> </div> </div> ) } }
父傳子
import進來的組件名是什麼,標籤名就是什麼,而後value這個key是隨便起的,但要跟Child組件裏的this.props.value一致就OK
好比
<Child str={this.state.father} />
對應的Child裏的獲取key要改爲<p>{this.props.str}</p> 這跟路由系統的to和path要一致是一個道理
子傳父
父組件Home2.js
import React from 'react'; import {Link} from "react-router-dom"; import Child from './Child'; export default class Home2 extends React.Component{ constructor(props){ super(props); this.state = { father: 'father', childValue: '' } } changeRoute = () => { this.props.history.push('/twoPage'); }; getChildValue = (val) => { if(val){ this.setState({ childValue: val }) } }; render(){ return ( <div> <div> <p>我是Home2組件</p> <Link to="/onePage">點我跳轉到one頁面</Link><br/> <Link to="/twoPage/2">點我跳轉到two頁面</Link><br/> <Link to="/this">點我跳轉到this頁面</Link> <p onClick={this.changeRoute}>點我試試</p> </div> <div> <p>我是父組件</p> <Child value={this.state.father} getChildValue={this.getChildValue} /> <p>{this.state.childValue}</p> </div> </div> ) } }
子組件Child.js:dom
import React from 'react'; export default class Child extends React.Component{ constructor(props){ super(props); this.state ={ child: 'child' } } forFatherValue = () => { this.props.getChildValue(this.state.child) }; render(){ return ( <div> <p>我是子組件</p> <p>{this.props.value}</p> <p onClick={this.forFatherValue}>點我給父組件傳遞參數</p> </div> ) } }
只須要在子組件標籤上添加父組件的事件,這個事件要能接收參數,子組件傳遞過來的值就在這個參數裏,還要注意子組件調用的是子組件的方法,方法內部纔是this.props.父組件綁定的key,這個key也是本身想取什麼均可以,綁定什麼key子組件方法內部就調用什麼key,多試幾遍就能記住。