天天看点

useContext一、useContext是什么?二、使用步骤

useContext

  • 一、useContext是什么?
  • 二、使用步骤
    • 1.引入库
    • 2.不用useContext
    • 3.useContext

提示:以下是本篇文章正文内容,下面案例可供参考

一、useContext是什么?

嵌套组件传值。

二、使用步骤

1.引入库

代码如下(示例):

import React from 'react'

export default React.createContext<any>(null)
           

2.不用useContext

代码如下(示例):

/**
 * 想要实现爷孙传参,这是一种,但比较麻烦————>①号
 */

import React from 'react'
import myContext from './index'

const Sunzi2 = () => {
  return <h3>
    Sunzi二号
    {/* ①号:如果有很多个孙子组件,每一个都要写这么多相同的 */}
    <myContext.Consumer>
      {
        (result) => {
          return <div>{result}</div>
        }
      }
    </myContext.Consumer>
  </h3>
}

// 想在孙子这获取到value
const Sunzi = () => {
  return <h3>
    Sunzi
    <myContext.Consumer>
      {
        (result) => {
          return <div>{result}</div>
        }
      }
    </myContext.Consumer>
  </h3>
}

const Child = () => {
  return <div>
    <h2>Child</h2>
    <Sunzi/>
    <Sunzi2/>
  </div>
}

const Parent = () => {
  return <div>
    <h1>Parent</h1>
    <myContext.Provider value={'我是传递的数据'}>
      <Child/>
    </myContext.Provider>
  </div>
}

export default Parent
           

3.useContext

/**
 * 想要实现爷孙传参,这是另一种,useContext
 */

import React, { useContext } from 'react'
import myContext from './index'

const Sunzi2 = () => {
  let context = useContext(myContext)
  return <h3>
    Sunzi二号
    {context}
  </h3>
}

// 想在孙子这获取到value
const Sunzi = () => {
  let context = useContext(myContext)
  return <h3>
    Sunzi
    {context}
  </h3>
}

const Child = () => {
  return <div>
    <h2>Child</h2>
    <Sunzi/>
    <Sunzi2/>
  </div>
}

const Parent = () => {
  return <div>
    <h1>Parent</h1>
    <myContext.Provider value={'我是传递的数据'}>
      <Child/>
    </myContext.Provider>
  </div>
}

export default Parent