父組件向子組件傳值?傳參,props接收
子組件向父組件傳值?回調函數
這裏重點說一下無關係組件之間的交互
React中沒有任何嵌套關係的組件之間如何傳值?
方案一:全局廣播的方式,即Publish/Subscribe,需要引入PubSubJS庫
鏈接:https://github.com/mroderick/PubSubJS
例子:
//主容器
var Main = React.createClass({
render : function(){
return (
<div>
<Head />
<List name="name1" />
<List name="name2" />
</div>
)
}
})
var Head = React.createClass({
getInitialState : function(){
return {
name : 'null'
}
},
componentDidMount : function(){
//監聽訂閱的事件
this.pubsub_token = PubSub.subscribe('name', function(topic, name){
this.setState({
name : name
})
}.bind(this))
},
componentWillUnmount : function(){
//銷燬監聽的事件
PubSub.unsubscribe(this.pubsub_token);
},
render : function(){
return (
<p>value : {this.state.name}</p>
)
}
})
var List = React.createClass({
//訂閱事件
onClick : function(){
PubSub.publish('name', this.props.name);
}
render : function(){
return (
<div onClick={this.onClick}>{this.props.name}</div>
)
}
})
注意:組件掛載完成,componentDidMount,再訂閱事件,而當組件卸載的時候,需要取消訂閱的事件,即componentWillUnmount
方案二:通過dispatchEvent事件觸發器,注意IE使用fireEvent替代
//to subscribe
otherObject.addEventListener('click', function(){alert('xxx')});
//to dispatch
this.dispatchEvent('click');
方案三:通過Signals,與dispatch類似,但是不能使用隨機的字符串作爲事件觸發的引用
//to subscribe
otherObject.clicked.add(function(){alert('xxx')});
//to dispatch
this.clicked.dispatch();
參考鏈接: