react组件间的数据传递

时间:2021-03-23 22:04:13

参考ReactJS组件间沟通的一些方法

父子组件

父->子:

通过props将数据传递给子组件

子->父

父组件通过props讲一个callback传给子组件,子组件内调用这个callback即可改变父组件的数据

兄弟组件

维护在父组件中

将数据维护在两个组件的父组件或祖先组件中通过props传递数据或者callback
但当组件层次较深的时候一层一层地传递数据太过繁琐

react组件间的数据传递

这个图笑死了……

全局事件

可以使用事件来实现组件间的沟通:改变数据的组件发起一个事件,使用数据的组件监听这个事件

  • 事件模块可以使用如EventEmitter或PostalJS这些第三方库。
  • 事件绑定和解绑可以分别放在componentDidMount和componentWillUnMount中。

使用事件模型,组件之间无论是父子关系还是非父子关系都可以直接沟通,从而解决了组件间层层回调传递的问题,但是频繁地使用事件实现组件间沟通会使整个程序的数据流向越来越乱,因此,组件间的沟通还是要尽量遵循单向数据流机制。

context

为了避免手动地将数据一层层地传递下去,可以使用context。
context可以让子组件直接访问组件的数据,无需从祖先组件一层层地传递数据到子组件中

class Parent extends component{
getChildContext() {
return {color: "purple"};
}
render(){
const children = this.props.messages.map((message) =>
<Button text={message.text} />
);
return <div>{children}</div>;
}
}

Parent.childContextTypes = {
color:PropTypes.string
}

这是父组件,我们为它添加了getChildContext()方法和childContextTypes 属性。
React自动地将color传递给子树中的任何组件。不过这个子组件必须定义contextTypes属性,不然获取到context为空。

class Button extends React.Component {
render() {
return (
<button style={{background: this.context.color}}>
{this.props.children}
</button>
);
}
}

Button.contextTypes = {
color: PropTypes.string
};

针对子组件Button,我们定义了contextTypes 属性,并在组件中通过 this.context.color直接获取到了color值。