使用TypeScript在React组件中的默认属性值

reactjs React.js

西门逆天

2020-03-11

我不知道如何使用Typescript为我的组件设置默认属性值。

这是源代码:

class PageState
{
}

export class PageProps
{
    foo: string = "bar";
}

export class PageComponent extends React.Component<PageProps, PageState>
{
    public render(): JSX.Element
    {
        return (
            <span>Hello, world</span>
        );
    }
}

当我尝试使用这样的组件时:

ReactDOM.render(<PageComponent />, document.getElementById("page"));

我收到一条错误消息,指出foo缺少属性我想使用默认值。我也尝试过static defaultProps = ...在组件内部使用,但是我怀疑它没有任何作用。

src/typescript/main.tsx(8,17): error TS2324: Property 'foo' is missing in type 'IntrinsicAttributes & IntrinsicClassAttributes<PageComponent> & PageProps & { children?: ReactEle...'.

如何使用默认属性值?我公司使用的许多JS组件都依赖于它们,不使用它们不是一种选择。

第740篇《使用TypeScript在React组件中的默认属性值》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
阳光村村 2020.03.11

在Typescript 2.1+中,使用Partial <T>而不是将接口属性设置为可选。

export interface Props {
    obj: Model,
    a: boolean
    b: boolean
}

public static defaultProps: Partial<Props> = {
    a: true
};

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android