您好,欢迎访问一九零五行业门户网

如何将react组件内数据进行共享

这次给大家带来如何将react组件内数据进行共享,将react组件内数据进行共享的注意事项有哪些,下面就是实战案例,一起来看一下。
利用react-redux实现react组件数据之间数据共享
1.安装react-redux
$ npm i --save react-redux
2.从react-redux导入proper组件将store赋予provider的store属性,
将根组件用provider包裹起来。
import {provider,connect} from 'react-redux'reactdom.render(<provider store={store}> <wrap/></provider>,document.getelementbyid('example'))
这样根组件中所有的子组件都可以获得store中的值
3.connect二次封装根组件
export default connect(mapstatetoprops,mapdispatchtoprops)(wrap)
connect接收两个函数作为参数,一个mapstatetoprops定义哪些store属性会被映射到根组件上的属性(把store传入react组件),一个mapdispatchtoprops定义哪些行为action可以作为根组件属性(把数据从react组件传入store)
3.定义这两个映射函数
function mapstatetoprops(state){ return {  name:state.name,  pass:state.pass }}function mapdispatchtoprops(dispatch){  return {actions:bindactioncreators(actions,dispatch) }}
把store中的name,pass映射到根组件的name,pass属性。
actions是一个包含了action构建函数的对象,用bindactioncreators把对象actions绑定到根组件actions属性上。
4.在根组件引用子组件的位置用 <show name={this.props.name} pass={this.props.pass}></show>将store数据传入子组件.
5.在子组件中调用actions中的方法来更新store中的数据
<input actions={this.props.actions} ></input>
先将actions作为属性传入子组件
子组件调用actions中的方法创建action
//input组件export default class input extends react.component{sure(){this.props.actions.add({name:this.refs.name.value,pass:this.refs.pass.value})} render(){   return (    <p>   姓名:<input ref="name" type="text"/>  密码:<input ref="pass" type="text"/>  <button onclick={this.sure.bind(this)}>登录</button> </p>  ) }}
因为我们采用了bindactioncreators函数,创建action后会立即自动调用store.dispatch(action)将数据更新到store.
这样我们就利用react-redux模块完成了react各个组件之间数据共享。
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
使用js操作图片只留黑白色
实战项目中如何使用vue组件
以上就是如何将react组件内数据进行共享的详细内容。
其它类似信息

推荐信息