useContext 跨文件组件传值
说明:父组件和子组件不在不同文件中,现需使用useContext实现父组件传值给子组件。
- 父组件
import React, { useState, createContext, useContext } from "react";
import ContentBox from "./ContentBox";
// 关键代码,创建createContext,并抛出去-------------------
export const BasisContext = createContext(null)
export default function MenuComponent() {
const [current, setCurrent] = useState("basis");
return (
<>
<div>
{/* 关键代码,传递current的值 ---------------------- */}
<BasisContext.Provider value={current}>
<ContentBox />
</BasisContext.Provider>
</div>
</>
);
}
- 子组件
import React, { useState, useCallback, useEffect, createContext, useContext } from "react";
import BasisBox from "./contentConponents/BasisBox";
// 关键代码,引入父组件中创建并抛出的 BasisContext
import {BasisContext} from './MenuComponent'
export default function ContentBox(props: any) {
// 关键代码:接收父组件传递过来的值
const name = useContext(BasisContext)
console.log("context name",name) // 输出:basis
return (
<>
<h2>{name}</h2>
</>
)
}