我不知道如何使用 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 组件都依赖它们,不使用它们不是一个选择。
带有类组件的默认 props
Using static defaultProps
是正确的。您还应该使用接口,而不是类来作为属性和状态。
更新2018/12/1:TypeScript 改进了与以下内容相关的类型检查defaultProps
随着时间的推移。继续阅读最新和最好的用法,直至较旧的用法和问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)