react组件数据传递方式总结

组件数据传递方式:

1. props

通过props进行数据传递,中间组件过渡props
缺点:props需要层层传递,难以管理维护

2.context

可实现跨级组件数据传递,不需要中间组件进行数据传递。
context 相当于一个全局变量,是一个大容器,我们可以把要通信的内容放在这个容器中,这样一来,不管嵌套有多深,都可以随意取用。需要满足以下条件:
1、父组件要声明自己支持 context,提供 context 中属性的 PropTypes
2、父组件需提供一个 getChildContext 函数,以返回一个初始的 context 对象
3、子组件要声明自己需要使用 context,并提供其需要使用的 context 属性的 PropTypes

// 父组件:提供 context
class Parent extends React.Component {
  // 第一步:constructor 构造函数,注意传递 context,super()注意第二个参数
  // 如果不适用 constructor ,可以忽略 这一步。
  constructor (props, context) {
    super(props, context)
    this.state = {
      color: 'red'
    }
  }

  // 第二步:声明自己 支持 context,提供 context 对象中的PropTypes
  static childContextTypes = {
    color: PropTypes.string,
    setColor: PropTypes.func
  }
  // 第三步:提供一个 getChildContext 函数,返回 初始 context 对象
  getChildContext = () => {
    return {
      color: this.state.color,
      setColor: this.handleSetColor
    }
  }

  handleSetColor = (color) => {
    this.setState({color})
  }

  render () {
    const {color} = this.state
    return <div>
      color:{color}
      <div>
        <Son/>
      </div>
      <Button onClick={() => this.handleSetColor('yellow')}>
        点击父元素
      </Button>
    </div>
  }
}

// 子组件
class Son extends React.Component {
  render () {
    return <div>
      <SonSon/>
    </div>
  }
}

// 孙组件:可 通过 context 对象,跨级 访问 父组件 的数据
class SonSon extends React.Component {
  // 第四步:子组件声明自己需要的使用context,并提供需要使用的 context PropsTypes
  static contextTypes = {
    color: PropTypes.string,
    setColor: PropTypes.func
  }

  handleClick = () => {
    const {color, setColor} = this.context
    setColor(color === 'red' ? 'green' : 'red')
  }

  render () {
    const {color} = this.context
    return <div>
      <div>
        sonson:{color}
      </div>
      <Button type={'primary'} onClick={this.handleClick}>点击我</Button>
    </div>
  }
}

3.redux

4.events

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值