模块化开发使用useContext
import React, { useState } from "react";
import Child1 from "./Child1";
import Child2 from "./Child2";
import MyContext from "./context";
export default function Index() {
const [state, setState] = useState({
name: "xx",
age: 24,
arr: [1, 2, 3],
});
return (
<div>
<h1>Home</h1>
<button
onClick={() => {
// 修改state中的数据,context向子组件传递的数据也会更新
setState((pre) => ({ ...pre, name: "lala" }));
}}
>
home-btn
</button>
<MyContext.Provider value={{ state, setState }}>
<Child1 />
<Child2 />
</MyContext.Provider>
</div>
);
}
// Child1 - 子组件
import { useContext } from 'react'
function Child1() {
// 这里的state、setState和父组件中声明的useState数据同步
const { state, setState } = useContext(MyContext); // MyContext 是上面引入的context
return <div>{state.name}</div>
}
// Child2 - 子组件
function Child2() {
// 这里的state、setState和父组件中声明的useState数据同步
const { state, setState } = useContext(MyContext); // MyContext 是上面引入的context
return <div>{state.name}</div>
}
上述 import 引入的 MyContext 可以直接在模块文件夹里面新建context.js
import React from "react";
const myContext = React.createContext({});
export default myContext;