Skip to content

buildContext ​

buildContext 是一个减少定义 React Context 时重复代码的辅助函数。

接口 ​

ts
function buildContext<ContextValuesType extends object>(
  contextName: string,
  defaultContextValues?: ContextValuesType
): [
  Provider: (props: ProviderProps<ContextValuesType>) => JSX.Element,
  useContext: () => ContextValuesType,
];

参数 ​

  • contextNamerequired · string

    Context 的名称。

  • defaultContextValuesContextValuesType

    传递给 Context 的默认值。

返回值 ​

  • [Provider: (props: ProviderProps<ContextValuesType>) => JSX.Element, useContext: () => ContextValuesType]

    具有以下形式的元组:

    • Provider(props: ProviderProps<ContextValuesType>) => JSX.Element

      提供 Context 的组件。

    • useContext() => ContextValuesType

      使用 Context 的 Hook。

示例 ​

tsx
const [Provider, useContext] = buildContext<{ title: string }>('TestContext', {
  title: 'Default title',
});

function Inner() {
  const { title } = useContext();
  return <div>{title}</div>;
}

function Page() {
  return (
    <Provider title="Hello">
      <Inner />
    </Provider>
  );
}

基于 MIT 许可证发布。