React 使用context向下传值

应用场景: 每个组件都需要获取登录的用户

相关知识点: createContext, 自定义Hooks, useContext

官方文档: https://zh-hans.reactjs.org/docs/context.html

项目地址: https://gitee.com/cjperfect/react_context

项目目录:
React 使用context向下传值_第1张图片

App.tsx

List和Header组件都能获取到AppProvider提供的参数, 前提是要被AppProvider包裹

React 使用context向下传值_第2张图片

import React from "react";
import Header from "./components/header";
import List from "./components/list";
import AppProvider from "./context/auth-provider";
import "./App.css";
// import { useAuth } from "./context/user-context";

function App() {
  // const context = useAuth();
  // console.log(context);
  return (
    <div className="App">
      <AppProvider>
        <Header />
        <List />
      </AppProvider>
    </div>
  );
}
export default App;

auth-provider.tsx

import React, { ReactNode } from "react";
import { AuthProvider } from "./user-context";

const AppProvider = ({ children }: { children: ReactNode }) => {
  return <AuthProvider>{children}</AuthProvider>;
};

export default AppProvider;

AuthProvider.tsx

也就是创建context的, 和真正的AppProvider分开, 好维护

import React, { ReactNode, useContext } from "react";

const AuthContext = React.createContext<
  | {
      name: "chenjiang";
      age: 24;
    }
  | undefined
>(undefined);
AuthContext.displayName = "AppContext";

export const AuthProvider = ({ children }: { children: ReactNode }) => {
  // AppProvider.tsx文件中传递了children, 这里需要接收
  return (
    <AuthContext.Provider
      value={{
        name: "chenjiang",
        age: 24,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error("请在AppProvider包裹的组件中使用");
  }
  return context;
};

Header.tsx

List和Header组件内部使用

import React from "react";
import { useAuth } from "../context/user-context";

const Header = () => {
  const context = useAuth();
  console.log("header", context);
  return (
    <header>
      header section===
      {"AppProvider传递过来的" + context.name}
    </header>
  );
};
export default Header;

你可能感兴趣的:(#,React学习,react.js,javascript,前端)