如果是父子组件之间的通信可以使用refs和props,代码如下
var YiTang = React.createClass({
sayFather: function () {
this.props.deliver();
console.log('MuTa, my father!');
},
test: function () {
console.log('父组件调用子组件');
},
render: function () {
return (
<div>
<h4>子组件</h4>
<button onClick={this.sayFather}>喊爸爸</button>
<button onClick={this.props.baba}>叫儿子</button>
</div>
);
}
});
var Muta = React.createClass({
getInitialState: function () {
console.log('getInitialState');
return {
value: 'sun',
time: 0
};
},
data: {
name: 'slm',
time: 0,
width: '200px'
},
getDefaultProps: function () {
console.log('getDefaultProps');
return {
title: 'evilemon'
};
},
handleClick: function () {
this.setState({
value: ''
});
this.data.time++;
this.refs.someName.getDOMNode().focus();
this.refs.child.test();
},
handleChange: function (event) {
this.setState({
value: event.target.value
});
this.add();
},
add: function () {
this.data.time++;
},
deliver: function () {
this.add();
this.forceUpdate();
},
sayChild: function () {
this.deliver();
console.log('Yitang, my son!');
},
render: function () {
var value = this.state.value;
return (
<div>
<input type="text" value={value} ref="someName" onChange={this.handleChange} />
<button onClick={this.handleClick}>清零</button>
<div style={{height: '100px', width: this.data.width, lineHeight: '100px'}}>{value}</div>
<div>操作次数 : {this.data.time}</div>
<div>{this.props.title}</div>
<br />
<YiTang ref="child" ref="child" baba={this.sayChild} deliver={this.deliver} click={this.add} />
</div>
);
}
});
React.render(<Muta title="MuTa"/>, document.body);
如果是两个层级以上的父子组件通信或者两个独立组件,应该使用pub/sub模式,react的关注点在componentDidMount
(用于注册事件)和componentWillUnmount(用于撤销事件);
var ProductList = React.createClass({
render: function() {
return <div>
<ProductSelection />
<Product name="product 1" />
<Product name="product 2" />
<Product name="product 3" />
</div>
}
});
var ProductSelection = React.createClass({
getInitialState: function() {
return { selection: 'none' };
},
componentWillMount: function() {
this.pubsub_token = pubsub.subscribe('products', function(topic, product) {
this.setState({ selection: product });
}.bind(this));
},
componentWillUnmount: function() {
pubsub.unsubscribe(this.pubsub_token);
},
render: function() {
return You have selected the product : {this.state.selection};
}
});
var Product = React.createClass({
onclick: function() {
pubsub.publish('products', this.props.name);
},
render: function() {
return <div onClick={this.onclick}>{this.props.name}</div>;
}
});
React.render(<ProductList />, document.body);//此段代码借鉴http://ctheu.com/2015/02/12/how-to-communicate-between-react-components/#child_to_parent
其实就是flux框架的原理。
done