React useContext的使用

188 阅读1分钟

React 使用useContext步骤

  1. 通过React.createContext创建
  2. 定义要传递的数据value={}
  3. Provider包裹要接收数据的组件
// 1: 通过createContext创建自己的context
const UserContext = createContext()
const App = () => {
  // 2: 定义要传递的数据
  const userInfo = { name: 'Master_y', age: 22 }
  return (
    // 3: xxx.Provider 包裹要接收数据的组件
    <UserContext.Provider value={userInfo}>
      <div>
        <Child1 />
      </div>
      <div>
        <Child2 />
      </div>
    </UserContext.Provider>
  )
}
  1. 在对应组件中通过React.useContext的方式接收数据
const Child1 = () => {
  // 4: 在对应组件中通过useContext的方式接收数据
  const { name } = useContext(userContext)
  return (
    <div className="container">
      <span>博客名:{name}</span>
    </div>
  )
}
const Child2 = () => {
  // 4: 在对应组件中通过useContext的方式接收数据
  const { age } = useContext(userContext)
  return (
    <div style={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
      <span>年龄:{age}</span>
    </div>
  )
}

完整例子

import React, { useContext } from 'react';

const styler = {
  width: '100%',
  display: 'flex',
  justifyContent: 'center',
  color: 'red',
  fontSize: 20,
};

export default () => {
  // 1: 通过createContext创建自己的context
  const UserContext = React.createContext();
  // 2: 定义要传递的数据
  const userInfo = { name: 'Master_y', age: 22 };

  const Child1 = () => {
    // 4: 在对应组件中通过useContext的方式接收数据
    const { name } = useContext(UserContext);
    return (
      <div style={styler}>
        <span>博客名:{name}</span>
      </div>
    );
  };

  const Child2 = () => {
    // 4: 在对应组件中通过useContext的方式接收数据
    const { age } = useContext(UserContext);
    return (
      <div style={styler}>
        <span>年龄:{age}</span>
      </div>
    );
  };

  return (
    // 3: xxx.Provider 包裹要接收数据的组件
    <UserContext.Provider value={userInfo}>
      <div>
        <Child1 />
      </div>
      <div>
        <Child2 />
      </div>
    </UserContext.Provider>
  );
};

image.png

实际生产中使用

import React from 'react';

export const MyContext = React.createContext();
export const MyProvider = ({ children, value }) => {
  return <MyContext.Provider value={value}>{children}</MyContext.Provider>;
};