类组件的默认道具
使用static defaultProps 是正确的。您还应该为道具和状态使用接口,而不是类。
2018 年 12 月 1 日更新:随着时间的推移,TypeScript 改进了与 defaultProps 相关的类型检查。继续阅读以了解最新和最有用的用法,直至旧用法和问题。
对于 TypeScript 3.0 及更高版本
TypeScript 专门added support for defaultProps 使类型检查按您的预期工作。示例:
interface PageProps {
foo: string;
bar: string;
}
export class PageComponent extends React.Component<PageProps, {}> {
public static defaultProps = {
foo: "default"
};
public render(): JSX.Element {
return (
<span>Hello, { this.props.foo.toUpperCase() }</span>
);
}
}
可以在不传递foo属性的情况下渲染和编译:
<PageComponent bar={ "hello" } />
注意:
对于 TypeScript 2.1 到 3.0
在 TypeScript 3.0 实现对 defaultProps 的编译器支持之前,你仍然可以使用它,并且它在运行时与 React 100% 工作,但由于 TypeScript 在检查 JSX 属性时只考虑道具,你必须标记道具使用? 将默认值设为可选。示例:
interface PageProps {
foo?: string;
bar: number;
}
export class PageComponent extends React.Component<PageProps, {}> {
public static defaultProps: Partial<PageProps> = {
foo: "default"
};
public render(): JSX.Element {
return (
<span>Hello, world</span>
);
}
}
注意:
- 用
Partial<> 注释 defaultProps 是个好主意,这样它就可以对你的 props 进行类型检查,但是你不必为每个必需的属性提供默认值,这没有任何意义,因为必需的属性应该永远不需要默认值。
- 使用
strictNullChecks 时,this.props.foo 的值将是possibly undefined,并且需要非空断言(即this.props.foo!)或类型保护(即if (this.props.foo) ...)来删除undefined。这很烦人,因为默认的 prop 值意味着它实际上永远不会未定义,但 TS 不理解这个流程。这是 TS 3.0 明确支持 defaultProps 的主要原因之一。
TypeScript 2.1 之前
这同样适用,但你没有 Partial 类型,所以只需省略 Partial<> 并为所有必需的道具提供默认值(即使这些默认值永远不会被使用)或完全省略显式类型注释.
你也可以在函数组件上使用defaultProps,但是你必须将你的函数输入到FunctionComponent(@types/react 之前版本@types/react 中的StatelessComponent)接口,以便TypeScript 知道defaultProps关于功能:
interface PageProps {
foo?: string;
bar: number;
}
const PageComponent: FunctionComponent<PageProps> = (props) => {
return (
<span>Hello, {props.foo}, {props.bar}</span>
);
};
PageComponent.defaultProps = {
foo: "default"
};
请注意,您不必在任何地方使用 Partial<PageProps>,因为 FunctionComponent.defaultProps 已在 TS 2.1+ 中指定为部分。
另一个不错的选择(这是我使用的)是解构您的 props 参数并直接分配默认值:
const PageComponent: FunctionComponent<PageProps> = ({foo = "default", bar}) => {
return (
<span>Hello, {foo}, {bar}</span>
);
};
那么你根本不需要defaultProps!请注意,如果您确实在函数组件上提供 defaultProps,它将优先于默认参数值,因为 React 将始终显式传递 defaultProps 值(因此参数永远不会未定义,因此从不使用默认参数。)所以你会使用其中一个,而不是两个。