美文网首页
react多组件通讯

react多组件通讯

作者: 未来在奋斗 | 来源:发表于2019-12-22 09:35 被阅读0次

不管是包裹还是写 contextType = myCtx的方法都要在const { Provider, Consumer } = myCtx包裹的情况下,父组件必须在包裹的情况下才能直接获取到props数据



import React from 'react'
import ReactDOM from 'react-dom'

//将React.createContext()方法拿到
const myCtx = React.createContext()
//只要将Provider包在父组件捡Consumer 包在子组件就能直接props数据
const { Provider, Consumer } = myCtx

class App extends React.Component {
  state = {
    color: 'red',
    fontSize: 16
  }
  
  render() {
    return (
      <Provider value={{
        color: this.state.color,
        fontSize: this.state.fontSize
      }} >
        <div>
          <h1>App</h1>
          <button onClick={
            () => {
              this.setState({
                color: 'green',
                fontSize: 34
              })
            }
          }>修改颜色为绿色</button>
          <hr />
          <One></One>
        </div>
      </Provider>
    )
  }
}

class One extends React.Component {
  render() {
    return (
      <div>
        <h2>One</h2>
        <hr />
        <Two></Two>
      </div>
    )
  }
}

class Two extends React.Component {
//子组件只要拿到就能接受到props数据
  static contextType = myCtx

  render() {
    console.log('========')
    console.log(this.context)
    return (
      <div>
        <h3 style={{ color: this.context.color }}>Two</h3>
        <hr />
        <Three></Three>
      </div>
    )
  }
}
// 或者这样写也可以
// Two.contextType = myCtx

class Three extends React.Component {
  render() {
    return (
      <Consumer>
        {
          (data) => {

            return (
              <div>
                <h4 style={{ color: data.color, fontSize: data.fontSize + 'px' }}>Three</h4>
              </div>
            )
          }
        }
      </Consumer>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'))

相关文章

  • react组件通信

    react组件通信是一个常用功能,在做react项目中经常遇到 React组件层级关系 在了解Reat组件通讯之前...

  • react父子通讯

    父子通讯父传数据给子,子传数据给父 react组件class 组件名 extends React.Componen...

  • react组件之间通信

    很感谢https://segmentfault.com/u/cwl提供的答案React 组件间通讯 说 React...

  • React父子组件之间如何通信?

    父组件向子组件通讯 通讯是单向的,数据必须是由一方传到另一方。在 React 中,父组件可以向子组件通过传 pro...

  • react-native-ble-plx 使用文档

    目前react-native关于蓝牙通讯的组件主要有 react-native-ble-manager 和 rea...

  • React native 组件间通讯

    一、父组件向子组件通讯通讯是单向的,数据必须是由一方传到另一方。在React中,父组件可以通过向子组件通过传pro...

  • 9天深入react(2-1)-Context

    组件跨层级通讯-Context Context API React.createContext 创建一个Con...

  • React基础

    React包含react元素和react组件 react元素 react组件 react组件分为函数组件和类组件 ...

  • React组件之间的通讯

    在 React 中,UI 以组件的形式来搭建,组件之间可以嵌套组合。另,React 中组件间通信的数据流是单向的,...

  • react组件之间的通讯

    背景故事很简单:父组件对子组件传递信息,直接使用props即可;子组建对父组件传递信息,参考自React 组件之间...

网友评论

      本文标题:react多组件通讯

      本文链接:https://www.haomeiwen.com/subject/tpminctx.html