我正在尝试在Typescript中创建一个带有可选props和defaultProps的无状态React组件(对于React Native项目).这对于vanilla JS来说是微不足道的,但是我对如何在TypeScript中实现它感到难过.
使用以下代码:
import React, { Component } from 'react';
import { Text } from 'react-native';
interface TestProps {
title?: string,
name?: string
}
const defaultProps: TestProps = {
title: 'Mr',
name: 'McGee'
}
const Test = (props = defaultProps) => (
<Text>
{props.title} {props.name}
</Text>
);
export default Test;
Run Code Online (Sandbox Code Playgroud)
调用<Test title="Sir" name="Lancelot" />"Lancelot爵士"按预期呈现,但<Test />什么都没有,什么时候输出"Mr McGee".
任何帮助是极大的赞赏.
我想defaultprops为我的纯功能组件定义,但我得到一个类型错误:
export interface PageProps extends React.HTMLProps<HTMLDivElement> {
toolbarItem?: JSX.Element;
title?: string;
}
const Page = (props: PageProps) => (
<div className="row">
<Paper className="col-xs-12 col-sm-offset-1 col-sm-10" zDepth={1}>
<AppBar
title={props.title}
zDepth={0}
style={{ backgroundColor: "white" }}
showMenuIconButton={false}
iconElementRight={props.toolbarItem}
/>
{props.children}
</Paper>
</div>
);
Page.defaultProps = {
toolbarItem: null,
};
Run Code Online (Sandbox Code Playgroud)
我知道我可以这样写:
(Page as any).defaultProps = {
toolbarItem: null,
};
Run Code Online (Sandbox Code Playgroud)
有没有更好的添加方式defaultProps?