1.父组件对子组件传值 利用props属性传值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| 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='cat'></Component> <h1>hello world!!!</h1> </div>, document.getElementById('app') );
|
2.子组件对父组件传值 简单来说就是利用回调来完成,比如下面例子,子组件来改变父组件的颜色
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| 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.同一父组件下平级组件间传值 ,简单一句话 子组件先传给父组件,父组件再传给那个子组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| 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') );
|