createContext

createContext 允许你创建组件可以提供或读取的 上下文

¥createContext lets you create a context that components can provide or read.

const SomeContext = createContext(defaultValue)

参考

¥Reference

createContext(defaultValue)

在任何组件之外调用 createContext 以创建上下文。

¥Call createContext outside of any components to create a context.

import { createContext } from 'react';

const ThemeContext = createContext('light');

请参阅下面的更多示例。

¥See more examples below.

参数

¥Parameters

  • defaultValue:当读取上下文的组件上方的树中没有匹配的上下文提供器时,你希望上下文具有的值。如果你没有任何有意义的默认值,请指定 null。默认值意味着作为 “最后一招” 回退。它是静态的,不会随时间改变。

    ¥defaultValue: The value that you want the context to have when there is no matching context provider in the tree above the component that reads context. If you don’t have any meaningful default value, specify null. The default value is meant as a “last resort” fallback. It is static and never changes over time.

返回

¥Returns

createContext 返回一个上下文对象。

¥createContext returns a context object.

上下文对象本身不包含任何信息。它表示其他组件读取或提供的上下文。通常,你会在上面的组件中使用 SomeContext.Provider 来指定上下文值,并在下面的组件中调用 useContext(SomeContext) 来读取它。上下文对象有几个属性:

¥The context object itself does not hold any information. It represents which context other components read or provide. Typically, you will use SomeContext.Provider in components above to specify the context value, and call useContext(SomeContext) in components below to read it. The context object has a few properties:

  • SomeContext.Provider 允许你向组件提供上下文值。

    ¥SomeContext.Provider lets you provide the context value to components.

  • SomeContext.Consumer 是另一种很少使用的读取上下文值的方法。

    ¥SomeContext.Consumer is an alternative and rarely used way to read the context value.


SomeContext.Provider

将你的组件封装到一个上下文提供器中,为内部的所有组件指定此上下文的值:

¥Wrap your components into a context provider to specify the value of this context for all components inside:

function App() {
const [theme, setTheme] = useState('light');
// ...
return (
<ThemeContext.Provider value={theme}>
<Page />
</ThemeContext.Provider>
);
}

属性

¥Props

  • value:你要传递给此提供器内读取此上下文的所有组件的值,无论有多深。上下文值可以是任何类型。在提供器内部调用 useContext(SomeContext) 的组件接收其上方最内层对应上下文提供器的 value

    ¥value: The value that you want to pass to all the components reading this context inside this provider, no matter how deep. The context value can be of any type. A component calling useContext(SomeContext) inside of the provider receives the value of the innermost corresponding context provider above it.


SomeContext.Consumer

useContext 存在之前,有一种更老的读取上下文的方法:

¥Before useContext existed, there was an older way to read context:

function Button() {
// 🟡 Legacy way (not recommended)
return (
<ThemeContext.Consumer>
{theme => (
<button className={theme} />
)}
</ThemeContext.Consumer>
);
}

虽然这种旧方法仍然有效,但新编写的代码应该使用 useContext() 读取上下文:

¥Although this older way still works, but newly written code should read context with useContext() instead:

function Button() {
// ✅ Recommended way
const theme = useContext(ThemeContext);
return <button className={theme} />;
}

属性

¥Props

  • children:一个功能。React 将使用与 useContext() 相同的算法确定的当前上下文值调用你传递的函数,并渲染你从此函数返回的结果。每当父组件的上下文发生变化时,React 也会重新运行此函数并更新 UI。

    ¥children: A function. React will call the function you pass with the current context value determined by the same algorithm as useContext() does, and render the result you return from this function. React will also re-run this function and update the UI whenever the context from the parent components changes.


用法

¥Usage

创建上下文

¥Creating context

上下文让组件 将信息传递到深处 无需显式传递属性。

¥Context lets components pass information deep down without explicitly passing props.

在任何组件外部调用 createContext 以创建一个或多个上下文。

¥Call createContext outside any components to create one or more contexts.

import { createContext } from 'react';

const ThemeContext = createContext('light');
const AuthContext = createContext(null);

createContext 返回一个上下文对象。组件可以通过将上下文传递给 useContext() 来读取上下文:

¥createContext returns a context object. Components can read context by passing it to useContext():

function Button() {
const theme = useContext(ThemeContext);
// ...
}

function Profile() {
const currentUser = useContext(AuthContext);
// ...
}

默认情况下,它们收到的值将是你在创建上下文时指定的默认值。但是,这本身并没有用,因为默认值永远不会改变。

¥By default, the values they receive will be the default values you have specified when creating the contexts. However, by itself this isn’t useful because the default values never change.

上下文很有用,因为你可以从组件中提供其他动态值:

¥Context is useful because you can provide other, dynamic values from your components:

function App() {
const [theme, setTheme] = useState('dark');
const [currentUser, setCurrentUser] = useState({ name: 'Taylor' });

// ...

return (
<ThemeContext.Provider value={theme}>
<AuthContext.Provider value={currentUser}>
<Page />
</AuthContext.Provider>
</ThemeContext.Provider>
);
}

现在 Page 组件及其内部的任何组件,无论多深,都会将传递的上下文值 “看到”。如果传递的上下文值发生变化,React 也会重新渲染读取上下文的组件。

¥Now the Page component and any components inside it, no matter how deep, will “see” the passed context values. If the passed context values change, React will re-render the components reading the context as well.

阅读有关读取和提供上下文的更多信息并查看示例。

¥Read more about reading and providing context and see examples.


从文件导入和导出上下文

¥Importing and exporting context from a file

通常,不同文件中的组件需要访问相同的上下文。这就是为什么通常在单独的文件中声明上下文。然后你可以使用 export 声明 使上下文可用于其他文件:

¥Often, components in different files will need access to the same context. This is why it’s common to declare contexts in a separate file. Then you can use the export statement to make context available for other files:

// Contexts.js
import { createContext } from 'react';

export const ThemeContext = createContext('light');
export const AuthContext = createContext(null);

然后,在其他文件中声明的组件可以使用 import 语句来读取或提供此上下文:

¥Components declared in other files can then use the import statement to read or provide this context:

// Button.js
import { ThemeContext } from './Contexts.js';

function Button() {
const theme = useContext(ThemeContext);
// ...
}
// App.js
import { ThemeContext, AuthContext } from './Contexts.js';

function App() {
// ...
return (
<ThemeContext.Provider value={theme}>
<AuthContext.Provider value={currentUser}>
<Page />
</AuthContext.Provider>
</ThemeContext.Provider>
);
}

这与 导入和导出组件 类似

¥This works similar to importing and exporting components.


故障排除

¥Troubleshooting

我找不到更改上下文值的方法

¥I can’t find a way to change the context value

像这样的代码指定了默认上下文值:

¥Code like this specifies the default context value:

const ThemeContext = createContext('light');

这个值永远不会改变。如果 React 在上面找不到匹配的提供器,它只会使用这个值作为回退。

¥This value never changes. React only uses this value as a fallback if it can’t find a matching provider above.

为了使上下文随时间变化,在上下文提供器中添加状态和封装组件。

¥To make context change over time, add state and wrap components in a context provider.


React 中文网 - 粤ICP备13048890号