國慶充電特輯:
堵車堵死,廢話不多說直接上菜。
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')
);
看效果
?
學會了吧,回見,繼續堵車!!!