我不知道如何使用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 = ...在组件内部使用,但是我怀疑它没有任何作用。
foo
static defaultProps = ...
src/typescript/main.tsx(8,17): error TS2324: Property 'foo' is missing in type 'IntrinsicAttributes & IntrinsicClassAttributes<PageComponent> & PageProps & { children?: ReactEle...'.
如何使用默认属性值?我公司使用的许多JS组件都依赖于它们,不使用它们不是一种选择。
使用static defaultProps是正确的。您还应该使用接口(而不是类)作为道具和状态。
static defaultProps
更新2018/12/1 :TypeScriptdefaultProps随着时间的推移改进了与类型相关的类型检查。继续阅读以获取最新和最佳用法,直至较旧的用法和问题。
defaultProps
TypeScript特别添加了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" } />
注意:
foo?: string
undefined
defaultProps: Pick<PageProps, "foo">
PageProps
@types/react
16.4.11
在TypeScript 3.0实施对defaultProps您的编译器支持之前,您仍然可以使用它,并且它在运行时可与React一起使用100%,但是由于TypeScript在检查JSX属性时仅考虑了props,因此您必须使用标记默认的props ?。例:
?
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<>
strictNullChecks
this.props.foo``possibly undefined``this.props.foo!``if (this.props.foo) ...``undefined``defaultProps
这是一样的,但是您没有Partial类型,因此只需忽略Partial<>并为所有必需的prop提供默认值(即使永远不会使用这些默认值),或者完全忽略显式类型注释。
Partial
props.html#functional-and-class- components)默认道具
您也可以defaultProps在函数组件上使用,但是必须在FunctionComponent(StatelessComponent在@types/react版本之前16.7.2)接口中键入函数,以便TypeScript知道defaultProps函数:
FunctionComponent
StatelessComponent
16.7.2
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+中已经将其指定为部分。
Partial<PageProps>
FunctionComponent.defaultProps
另一个不错的替代方法(这是我使用的方法)是对props参数进行解构并直接分配默认值:
props
const PageComponent: FunctionComponent<PageProps> = ({foo = "default", bar}) => { return ( <span>Hello, {foo}, {bar}</span> ); };
然后,您根本不需要defaultProps!请注意,如果您 确实 提供defaultProps了功能组件,它将优先于默认参数值,因为React始终会显式传递defaultProps值(因此,永远不会未定义参数,因此永远不会使用默认参数。)因此,您将使用一个或另一个,而不是两者兼而有之。