主要和 React.createContext 配合使用。
用于组件传值,一般会单独使用一个文件,使用 React.createContext() 生成一个 context 对象,再通过 useContext 来管理分发数据,类似于 vue 的 bus。
类组件中使用 Consumer 标签包裹使用,函数式组件则使用 useContext()。
创建使用 Context 提供服务的文件:
// myContext.js 文件中创建
import React from 'react';
export default React.createContext();
父组件引入并挂载:
import React from 'react'
import MyContext from './MyContext';
// 子组件
import Home from './pages/Home'
function App() {
const [state, setState] = React.useState(1)
// 自定义的一个方法
function add1() {
setState(state => state + 1)
}
return (
<div className="App">
{/* 这里注意,需要使用组件 Provider 标签来包裹需要用到服务的子们标签 */}
<MyContext.Provider value={{ state, add1 }}>
<Home />
</MyContext.Provider>
</div>
);
}
export default App;
函数式子组件中使用:
用法一:使用 <MyContext.Consumer> 标签:
import React from 'react';
import MyContext from '../../MyContext';
function Home() {
return (
// 此标签包裹的应该是一个方法,会把传入的字段作为参数传入
<MyContext.Consumer>
{
({state, add1}) => {
return (
<>
{state}
<button onClick={add1}>点击修改</button>
</>
)
}
}
</MyContext.Consumer>
)
}
export default Home
用法二:使用 useContext 方法得到:
import React from 'react';
import MyContext from '../../MyContext';
function Home() {
// 从 MyContext 得到传过来的数据和方法
const {state, add1} = React.useContext(MyContext)
return (
<>
{state}
<button onClick={add1}>点击修改</button>
</>
)
}
export default Home