Context 提供了一个无需为每层组件手动添加 props,就能在组件树间进行数据传递的方法。
React 提供了 createContext
这个 API 来创建 Context 实例。createContext 的函数签名是:createContext(value: any): {Provider, Consumer}
。
React 提供了 2 种方式来消费 createContext 创建的 Context 数据:
import React, { createContext } from "react";
const ThemeContext = createContext({ theme: "light" });
const ThemeText = () => {
return <ThemeContext.Consumer>
{({theme}) => (
<button>Current theme is: {theme}</button>
)}
</ThemeContext.Consumer>
}
class App extends React.Component {
render() {
return <ThemeContext.Provider value={{theme: 'dark'}}>
<ThemeText />
</ThemeContext>
}
}
import { themeContext } from "./themeContext";
class MyClass extends React.Component {
componentDidMount() {
let value = this.context;
/* 在组件挂载完成后,使用 MyContext 组件的值来执行一些有副作用的操作 */
}
componentDidUpdate() {
let value = this.context;
/* ... */
}
componentWillUnmount() {
let value = this.context;
/* ... */
}
render() {
let value = this.context;
/* 基于 MyContext 组件的值进行渲染 */
}
}
MyClass.contextType = themeContext;
使用方式:
import React, { createContext, useContext } from "react";
const ThemeContext = createContext({ theme: "light" });
function Button() {
const { theme } = useContext(ThemeContext);
return <div>current theme is { theme }</div>;
}