react --- > 隔代传递参数的三种方式

组件跨层级通信 - Context

  • 上下文提供一种不需要每层设置props就能跨多级组件传递数据的方式

方式1

  • Provider提供值
  • Consumer来消费传递的值
import React from 'react';

// 创建一个上下文
const Mycontext = React.createContext();
const { Provider, Consumer } = MyContext;

function Child(prop) {
  return <div>Child: {prop.foo} </div>
}

export default function ContextTest() {
  return (
    <div>
      <Provider value ={ {foo: 'bar'} }>
        <Consumer>
          // 将value的孩子展开
          {value => <Child {...child} />}
        </Consumer>
      </Provider>
    </div>
  )
}

方式2

  • 使用hook来消费(useContext)
import React, {useContext} from 'react';
const { Provider } = MyContext;

const MyContext = React.createContext();

// 使用hook消费
function Child2() {
  // 使用useContext来获取传递过来的参数,放在ctx里面
  const ctx = useContext(MyContext);
  return <div>Child2: {ctx.foo} </div>
}

export default function ContextTest() {
  return (
    <div>
      <Provider value={{foo: 'bar'}}>
       <Child2></Child2>
      </Provider>
    </div>
  )
}

方式3

  • 使用class指定静态contextType
import React from 'react'
const MyContext = React.createContext();

class Child3 extends React.Component{
  static contextType = MyContext;
  render(){
    return <div>
      Child3: {this.context.foo}
    </div>
  }
}

export default function ContextTest() {
  return (
    <div>
      <Provider value={{foo: 'bar'}}>
       <Child3></Child3>
      </Provider>
    </div>
  )
}

你可能感兴趣的:(react,组件传递参数,react,hook,钩子)