react hooks入门 -useContext

Hooks全部入门

useState

useEffect

useContext

useRef

重要:自定义hooks

context可以看作是上下文
是什么:

  1. 创建一个上下文环境,在上下文环境中保持变量

怎么用:
2. 创建context -> createContext
3. 使用Provider圈定作用域
4. 在作用域内使用useContext来使用上下文

demo

import React, { createContext, useContext, useState } from 'react';

const C = createContext(null);

function useContextDemo() {
  const [ n, setN ] = useState(0);
  return (
    <C.Provider value={{n, setN}}>
      <div>
        <Parent />
      </div>
    </C.Provider>
  )
}

function Parent() {
  const {n} = useContext(C);
  return (
    <div>
      this is parent
      <p>this is n in parent :{ n}</p>
      <ChildA />
      <ChildB />
    </div>
  )
}

function ChildA() {
  const {n, setN} = useContext(C);
  return (
    <div>
      this is child
      <p>this is n in childA :{ n}</p>
      <button onClick={() => { setN(n + 1) }}>+1</button>
    </div>
  )
}


function ChildB() {
  const {n, setN} = useContext(C);
  return (
    <div>
      this is child
      <p>this is n in childB :{ n}</p>![在这里插入图片描述](https://img-blog.csdnimg.cn/2020042120203162.gif)
      <button onClick={() => { setN(n + 1) }}>+1</button>
    </div>
  )
}

export default useContextDemo;
  1. 首先第三行使用createContext创建一个context并赋值给C
  2. 在最外层组件使用C.Provider包裹要使用的组件
  3. 在ChildA组件和ChildB组件分别引入context结构出来的n和setN
  4. 在Provider范围内的点击任意一个按钮都可以实现setN的效果,并且在任意位置使用n都可以获取到n
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值