簡單教你React父子元件間平級元件間傳值
阿新 • • 發佈:2019-02-08
國慶充電特輯:
堵車堵死,廢話不多說直接上菜。
1.父元件對子元件傳值 利用props屬性傳值
class Component extends React.Component { constructor (props) { super(props); } render() { return ( <div> <h1>I am {this.props.name}</h1> </div> ); } } ReactDOM.render( <div> <Component name='YUSIRXIAER'></Component> <h1>hello world!!!</h1> </div>, document.getElementById('app') );
效果如圖 爸爸的凝視,會了沒(手動滑稽)
2.子元件對父元件傳值 簡單來說就是利用回撥來完成,比如下面例子,子元件來改變父元件的顏色
// 處理父子元件間傳值 class Child extends React.Component { constructor (props) { super(props); } handleClick() { this.props.colorChange('yellow') } render() { return ( <div> <h1>父元件的值 {this.props.bgColor}</h1> <button onClick={(e) => this.handleClick(e)}>改變父元件顏色</button> </div> ); } } class Father extends React.Component { constructor (props) { super(props); this.state={ bgColor: '#999' }; } onBgColorChange(color) { this.setState({ bgColor: color }) } render() { return ( <div style={{background:this.state.bgColor}}> <Child bgColor={this.state.bgColor} colorChange={(color)=>{this.onBgColorChange(color)}}></Child> {/* 子元件像父元件傳值,設定回撥 */} </div> ); } } ReactDOM.render( <div> <Father></Father> </div>, document.getElementById('app') );
看效果
3.同一父元件下平級元件間傳值 ,簡單一句話 子元件先傳給父元件,父元件再傳給那個子元件
// 處理平級元件間傳值 ,先傳給父元件,父元件再傳給另一個元件 class Child1 extends React.Component { constructor (props) { super(props); } handleClick() { this.props.changeChild2Color('yellow') } render() { return ( <div> <h1>Child1: {this.props.bgColor}</h1> <button onClick={(e) => this.handleClick(e)}>向Child2傳值,改變其顏色</button> </div> ); } } class Child2 extends React.Component { constructor (props) { super(props); } render() { return ( <div style={{background:this.props.bgColor}}> <h1>Child2: {this.props.bgColor}</h1> </div> ); } } class Father extends React.Component { constructor (props) { super(props); this.state={ child2BgColor: '#999' }; } onChild2BgColorChange(color) { this.setState({ child2BgColor: color }) } render() { return ( <div> {/* 平級元件間傳值*/} <Child1 changeChild2Color={(color)=>{this.onChild2BgColorChange(color)}}></Child1> <Child2 bgColor={this.state.child2BgColor}></Child2> </div> ); } } ReactDOM.render( <div> <Father></Father> </div>, document.getElementById('app') );
看效果
學會了吧,回見,繼續堵車!!!