1.父组件的设置
//创建一个context对象
export const MyContext = createContext(null);
function Parent() {
const [param, setParam] = useState(0);
return (
// 用MyContext.Provider包括的元素,里面所有的子组件都能获取到value里面的值
<MyContext.Provider value={{ param, setParam }}>
<Son1 />
<Son2 />
</MyContext.Provider>
);
}
export default Parent;
2.子组件1,更新param的值
//从父组件引入context对象
import { MyContext } from "./Parent";
function Son1() {
//获取value的值
const { param, setParam } = useContext(MyContext);
useEffect(() => {
setParam(1);
}, []);
return <></>;
}
export default Son1;
3.子组件2最终会获取到更新后的值
//从父组件引入context对象
import { MyContext } from "./Parent";
function Son2() {
//获取value的值
const { param, setParam } = useContext(MyContext);
console.log(param);//最后会打印1
return <></>;
}
export default Son2;
当组件嵌套过多时,建议使用context