父组件向子组件通信
React中数据的流动是单向的,父组件向子组件的通信是最常见的组件间通信形式,即父组件通过props
传递子组件信息。
例如:
class App extends Component{
render(){
return (
<div>
<Controlled inputState="Hello World"/>
</div>
)
}
}
class Controlled extends Component{
constructor(props){
super(props);
this.state = {
inputState: this.props.inputState
}
this.changeHandle = this.changeHandle.bind(this);
}
changeHandle(e){
this.setState({
inputState: e.target.value.toUpperCase()
});
}
render(){
const {inputState} = this.state;
return (
<div>
<input type='text' value={inputState} onChange={this.changeHandle}></input>
</div>
)
}
}
可以看出上面的代码中,Controlled
子组件通过父组件传入的inputState props
获得初值。
子组件向父组件通信
子组件想要向父组件通信通常有有两种方式:
- 回调函数
- 利用自定义事件机制
回调函数
class App extends Component{
constructor(props){
super(props);
this.state = {
inputState: ''
};
}
changeHandle(e){
this.setState({
inputState: e.target.value.toUpperCase()
});
}
render(){
return (
<div>
<Controlled inputState={this.state.inputState} changeHandle={this.changeHandle.bind(this)}/>
</div>
)
}
}
class Controlled extends Component{
constructor(props){
super(props);
this.changeHandle = this.props.changeHandle;
}
render(){
const {inputState} = this.props;
return (
<div>
<input type='text' value={inputState} onChange={this.changeHandle}></input>
</div>
)
}
}
Controlled
子组件中的状态通过由父组件传入的changeHandle
回调函数获得,并在父组件中将该状态写回子组件。实现了“跨层级”的数据双向绑定。
利用自定义事件机制
所谓的自定义事件机制就是常见的发布/订阅模式。可以使用Node.js Events
模块的浏览器版实现。
class App extends Component{
constructor(props){
super(props);
this.state = {
inputState: ''
};
}
componentDidMount(){
emitter.addListener('change', (msg)=>{
this.setState({
inputState: msg
});
});
}
componentWillUnmount(){
emitter.removeAllListeners('change');
}
render(){
return (
<div>
<Controlled inputState={this.state.inputState} />
</div>
)
}
}
class Controlled extends Component{
constructor(props){
super(props);
this.changeHandle = this.changeHandle.bind(this);
}
changeHandle(e){
emitter.emit('change', e.target.value);
}
render(){
const {inputState} = this.props;
return (
<div>
<input type='text' value={inputState} onChange={this.changeHandle}></input>
</div>
)
}
}
还是实现了跟回调函数例子中相同的功能,只不过使用了自定义事件。