【问题标题】:React Typescript Class Component Default Props InterfaceReact Typescript 类组件默认道具接口
【发布时间】:2019-12-27 22:38:01
【问题描述】:

我用一些道具创建了一个简单的类组件。从 Typescript 3 及更高版本开始,他们声明 defaultProps 默认将使用与组件的 props 本身相同的接口。 reference

在下面的代码示例中,您可以看到我创建了一个组件,使用给定接口扩展了 React.PureComponent。一个 prop 称为 boolean,类型为 boolean。

然后我得到了static defaultProps 分配,我在其中输入了一个字符串而不是布尔值。

import React from "react";

export interface ExampleClassProps {
  string: string;
  arrayOfStrings: { test: string };
  boolean: boolean;
}

class ExampleClass extends React.PureComponent<ExampleClassProps> {
  static defaultProps = {
    string: "asd",
    arrayOfStrings: { test: "asd" },
    boolean: "true" //this should throw an error, since I'm assigning a string to type boolean
  };
  render() {
    return <div>{this.props.string}</div>;
  }
}
export default ExampleClass;

根据我的理解,Typescript 现在应该抛出一个错误,说 type string is not assignable to type boolean,但事实并非如此。

我使用的是 Typescript 3.5.3,我安装了 @types/react。

另外,编写一个类似的组件作为功能组件确实有效,所以我只遇到了类的问题:

import React from "react";

export interface ExampleFCProps {
  stringProp?: string;
}

const ExampleFC: React.FC<ExampleFCProps> = ({ stringProp }) => {
  return <div>{stringProp}</div>;
};

ExampleFC.defaultProps = { stringProp: 1 }; //this throws an error, since number is not type string

export default ExampleFC;

【问题讨论】:

    标签: reactjs typescript class components


    【解决方案1】:

    我认为documentation you referenced 的含义并非如此。它是这样说的:

    默认属性是从defaultProps 属性类型推断出来的。

    我认为这意味着它查看defaultProps 属性并从其值推断类型:它不查看组件的props 的类型。这是有道理的,因为如果它确实假设 defaultPropsprops 具有相同的类型,那么默认情况下你永远不能只提供部分道具:defaultProps 总是必须为 提供一个值props 中的所有内容

    文档对这种情况的建议是这样的:

    使用static defaultProps: Pick&lt;Props, "name"&gt;; 作为显式类型 代替注释,或者不添加类型注释,如 上面的例子。

    在您的示例中,如果您想为每个 prop 提供默认值并对其进行类型检查,请明确告诉编译器 defaultProps 的类型为 ExampleClassProps

    class ExampleClass extends React.PureComponent<ExampleClassProps> {
        static defaultProps: ExampleClassProps = { // <-- explicitly state the type
            string: "asd",
            arrayOfStrings: { test: "asd" },
            boolean: "true" //this now does not compile, since you're assigning a string to type boolean
        };
    

    顺便说一句,这里有一个有趣的提示:https://medium.com/@martin_hotell/10-typescript-pro-tips-patterns-with-or-without-react-5799488d6680。请参阅名为“9. 使用类型推断来定义组件状态或 DefaultProps”的部分。

    【讨论】:

    • 嗯,好像我对文档的理解有误,非常感谢!
    猜你喜欢
    • 2020-01-25
    • 2020-12-21
    • 2020-03-14
    • 2013-09-09
    • 2018-05-26
    • 2016-05-06
    • 2019-07-27
    • 2019-06-30
    • 2016-12-11
    相关资源
    最近更新 更多