React 入門學習筆記整理(六)—— 元件通訊
阿新 • • 發佈:2018-12-20
1、父子元件通訊
1)父元件與子元件通訊,使用Props
父元件將name傳遞給子元件
<GreateH name="kitty"/>
子元件通過props接收父元件的值,並顯示
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)子元件與父元件通訊,執行回撥函式
如圖所示,點選子元件按鈕改變父元件中標題顏色
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事件改變對應標題的顏色
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;
2、兄弟元件通訊
如圖所示,要實現點選B元件的按鈕改變A的名稱,點選A元件的按鈕改變B元件的名稱
父元件:
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元件:
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>
}
}
學到這裡有個問題,為什麼這樣寫沒有用:
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>
}
}
這個問題,等學到後面再來解決