For AI agents: the complete documentation index is available at /next/zh/llms.txt, the full documentation bundle is available at /next/zh/llms-full.txt, and this page is available as Markdown at /next/zh/api/react/Functions/createContext.md.
  • 简体中文
  • 函数: createContext()

    createContext<T>(defaultValue: T): Context<T>

    让你创建一个组件可以提供或读取的 Context。

    类型参数

    类型参数
    T

    参数

    参数类型描述
    defaultValueT当读取 context 的组件在其上层树中找不到匹配的 Provider 时,你希望 context 具有的值。它作为“最后兜底”使用。

    返回

    Context<T>

    参阅

    示例

    import { createContext } from 'react';
    
    const ThemeContext = createContext('light');
    function App() {
      return (
        <ThemeContext value="dark">
          <Toolbar />
        </ThemeContext>
      );
    }
    除非另有说明,本项目采用知识共享署名 4.0 国际许可协议进行许可,代码示例采用 Apache License 2.0 许可协议进行许可。