react-hooks中useContext的使用

react-hooks中useContext的使用

1、作用

useContext可以多层嵌套传输数据和方法

2、使用

1、新建一个store.js文件,使用React.createContext()创建一个自己的Context

import React from "react";
const myContext = React.createContext(null);

export { myContext };

2、最外层组件

使用myContext.Provider包裹然后value传入自己需要的值

import { myContext } from "./store";
import React, { useState } from "react";
import Child from "./child";
const App = () => {
  const [num, setNum] = useState(0);
  return (
    <myContext.Provider value={{ setNum, num }}>
      <Child></Child>
    </myContext.Provider>
  );
};

export default App;

3、子组件

引入myContext并通过useContext获取到传入的值

import { myContext } from "./store";
import React, { useContext} from "react";
import GrandSon from "./grandSon";

const Child = (props) => {
  const { setNum, num } = useContext(myContext);
  return (
    <>
      <h1>{num}</h1>
      <button
        onClick={() => {
          setNum((prev) => prev + 1);
        }}
      >
        添加
      </button>
      <GrandSon num={num} />
    </>
  );
};

export default Child;

3、孙组件

和子组件中一样

import { myContext } from "./store";
import React, { useContext } from "react";

const GrandSon = (props) => {
  const { setNum, num } = useContext(myContext);
  return (
    <>
      <h1>我是孙子</h1>
      <h1>{num}</h1>
      <button
        onClick={() => {
          setNum((prev) => prev + 1);
        }}
      >
        添加
      </button>
    </>
  );
};

export default GrandSon;

多层传值的话结构比较清晰,不需要层层用props传值,在一个单独的组件中传值中比较方便

你可能感兴趣的:(react,react.js)