1)父組件與子組件通訊,使用Props
父組件將name傳遞給子組件函數
<GreateH name="kitty"/>
子組件經過props接收父組件的值,並顯示this
class GreateH extends React.Component{ static defaultProps = { name:'CoCo' }; constructor(props){ super(props); this.state ={ name:props.name } } render(){ return <div> <h2>hello,{this.state.name}</h2> </div> } }
2)子組件與父組件通訊,執行回調函數
如圖所示,點擊子組件按鈕改變父組件中標題顏色3d
class GreateH extends React.Component{ static defaultProps = { name:'CoCo' }; constructor(props){ super(props); this.state ={ name:props.name } } changeBtn(){ if(typeof this.props.click == 'function' ){ //觸發父組件的事件,改變父組件中標題顏色 this.props.click(); } }; render(){ return <div> <h2>hello,{this.state.name}</h2> <button onClick={this.changeBtn.bind(this)}>點擊改變標題顏色</button> </div> } } export default GreateH;
父組件中經過changeColor事件改變對應標題的顏色code
class App extends Component { changeColor(obj){ var oDom = document.getElementsByClassName(obj.class)[0]; oDom.style.color = obj.color; }; render() { return ( <div className="App"> <h2 className="title1">子組件一</h2> <GreateH name="kitty" click={this.changeColor.bind(this,{color:'red',class:'title1'})}/> <hr/> <h2 className="title2">子組件二</h2> <GreateH name="lily" click={this.changeColor.bind(this,{color:'blue',class:'title2'})}/> </div> ); } } export default App;
如圖所示,要實現點擊B組件的按鈕改變A的名稱,點擊A組件的按鈕改變B組件的名稱
blog
父組件:事件
class App extends Component { constructor(props){ super(props); this.state = { nameA:'kitty', nameB:'Lily' } } changeBName(params){ this.setState({ nameB:params }) } changeAName(params){ this.setState({ nameA:params }) } render() { return ( <div className="App"> <h2 className="title1">組件A</h2> <GreateA name={this.state.nameA} click={this.changeBName.bind(this)}/> <hr/> <h2 className="title2">組件B</h2> <GreateB name={this.state.nameB} click={this.changeAName.bind(this)}/> </div> ); } }
A組件:get
class GreateH extends React.Component{ static defaultProps = { name:'' }; changeBtn(){ if(typeof this.props.click == 'function' ){ this.props.click('kristy'); } }; render(){ return <div> <h2>hello,{this.props.name}</h2> <button onClick={this.changeBtn.bind(this)}>點擊改變B組件的名字</button> </div> } }
B組件回調函數
class GreateH extends React.Component{ static defaultProps = { name:'' }; changeBtn(){ if(typeof this.props.click == 'function' ){ this.props.click('CoCo'); } }; render(){ return <div> <h2>hello,{this.props.name}</h2> <button onClick={this.changeBtn.bind(this)}>點擊改變A組件的名字</button> </div> } }
學到這裏有個問題,爲何這樣寫沒有用:it
class GreateH extends React.Component{ static defaultProps = { name:'' }; constructor(props){ super(props); this.state ={ name:this.props.name } } changeBtn(){ if(typeof this.props.click == 'function' ){ this.props.click('CoCo'); } }; render(){ return <div> // 改爲this.props.name以後才能檢測到變化 <h2>hello,{this.state.name}</h2> <button onClick={this.changeBtn.bind(this)}>點擊改變A組件的名字</button> </div> } }
這個須要加一個鉤子函數,在鉤子函數中去改變state的值,以下:io
static getDerivedStateFromProps(props,state){ return { name:props.name } }