【问题标题】:TypeScript typing for dynamic react context用于动态反应上下文的 TypeScript 类型
【发布时间】:2020-01-21 17:56:07
【问题描述】:

我正在创建一个新的上下文 export const SchemaContext = React.createContext(null);

上下文对象创建到组件中,该组件将成为上下文的一部分。

type TSchemaProps<M = {}}> = {
  model: M
};


export const Schema = <M,>({
  model: globalModel
}: TSchemaProps<M>) => {
  const [model] = useState<M>(globalModel);

  const context = {
    model,
    isRoot: true
  };

  return (
    <SchemaContext.Provider value={context}> // Type { model: M } is not assignable to null
      {children}
    </SchemaContext.Provider>
  );
};

现在我们可以使用 JSX 泛型来打字了

type TModel = {
    docNum: number,
    docDate: number,
    group: {
        kpp: string,
        orgn: string
    }
};

const MainComp = () => {
  <Schema<TModel> />
}

如何将 TModel 传递给上下文类型?

【问题讨论】:

    标签: reactjs typescript typescript-generics


    【解决方案1】:

    您可以在生成上下文时将generic 传递给createContext 以定义其值的类型。

    type TModel = {
        docNum: number,
        docDate: number,
        group: {
            kpp: string,
            orgn: string
        }
    };
    
    ...
    
    export const MyContext = createContext<TModel | SomeOtherType>(defaultValues);
    

    【讨论】:

    • 我可以使用一些Models,但可以使用一个Context
    • 什么意思?你可以使用任何你想要的类型或接口,你只需要将它作为泛型传递给createContext
    • 我不知道我将使用哪个接口。我可以更改界面或输入Schema 组件吗?类似const Context = MyContext.Consumer as M
    • 您需要传入多种类型,或者构建一个类型来说明您可能需要的所有数据。我更新了我的答案,以展示如何使用 2 种不同的类型。我建议阅读 Partialintersection types,因为它们是不同的主题。
    • 所以如果我有 1000 个模型,我需要编写 1000 个交集或创建 1000 个不同模型的上下文,对吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 2022-08-23
    • 1970-01-01
    • 2019-06-10
    • 2021-01-20
    • 2020-06-28
    • 2020-04-03
    相关资源
    最近更新 更多