react组件间的数据传递
2017-08-01 12:00
393 查看
参考ReactJS组件间沟通的一些方法
但当组件层次较深的时候一层一层地传递数据太过繁琐
这个图笑死了……
事件模块可以使用如EventEmitter或PostalJS这些第三方库。
事件绑定和解绑可以分别放在componentDidMount和componentWillUnMount中。
使用事件模型,组件之间无论是父子关系还是非父子关系都可以直接沟通,从而解决了组件间层层回调传递的问题,但是频繁地使用事件实现组件间沟通会使整个程序的数据流向越来越乱,因此,组件间的沟通还是要尽量遵循单向数据流机制。
context可以让子组件直接访问组件的数据,无需从祖先组件一层层地传递数据到子组件中
这是父组件,我们为它添加了getChildContext()方法和childContextTypes 属性。
React自动地将color传递给子树中的任何组件。不过这个子组件必须定义contextTypes属性,不然获取到context为空。
针对子组件Button,我们定义了contextTypes 属性,并在组件中通过 this.context.color直接获取到了color值。
父子组件
父->子:
通过props将数据传递给子组件子->父
父组件通过props讲一个callback传给子组件,子组件内调用这个callback即可改变父组件的数据兄弟组件
维护在父组件中
将数据维护在两个组件的父组件或祖先组件中通过props传递数据或者callback但当组件层次较深的时候一层一层地传递数据太过繁琐
这个图笑死了……
全局事件
可以使用事件来实现组件间的沟通:改变数据的组件发起一个事件,使用数据的组件监听这个事件。事件模块可以使用如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值。
相关文章推荐
- react之使用Context跨组件树传递数据
- react---组件间数据传递
- java后台传递json数据到前端并渲染react组件(react+struts2)
- React学习:组件生命周期、组件间数据传递
- React学习(二)——组件的运用和数据传递
- react(二)父子组件间的数据传递---prop
- React Native学习笔记之--组件之间数据的传递和跳转
- React 的数据流动(反向由子组件向父组件传递数据)
- job-React 组件之间的传递数据
- react都这么无情了,vue还是那么有义,4种父子组件数据双向传递大法
- React数据传递之组件内部通信的方法
- React技巧7(TodoList实现3组件之间传递数据之优化)
- react.js 组件之间的数据传递props
- 综述种类:Android组件之间 数据传递方法
- angular2父子组件的数据传递,子组件向父组件抛出数据
- Vue之父组件向子组件传递数据
- 续-React数据传递-props
- 从零开始 React Native (5) React 数据传递_表单_函数复用_动画
- 设计数据层组件并在层间传递数据(MS)
- 如何存储 React 组件的数据