[英]TypeScript + React: defining defaultProps correctly
假设您像这样定义组件:
interface IProps {
req: string;
defaulted: string;
}
class Comp extends React.Component<IProps, void> {
static defaultProps = {
defaulted: 'test',
};
render() {
const { defaulted } = this.props;
return (
<span>{defaulted.toUpperCase()}</span>
);
}
}
当你想使用它时,TypeScript想要你的defaulted
道具,即使它是在defaultProps
定义的:
<Comp req="something" /> // ERROR: TypeScript: prop 'defaulted' is required
但是,如果你像这样定义道具界面:
interface IProps {
req: string;
defaulted?: string; // note the ? here
}
然后你不能用它:
render() {
const { defaulted } = this.props; // ERROR: prop 'defaulted' possibly undefined
return (
<span>{defaulted.toUpperCase()}</span>
);
}
如何正确定义IProps,defaultProps和组件以使类型有意义?
编辑:
我正在使用strictNullChecks
标志。
我有一个使用以下代码的示例(ComponentBase只是我的React.Component包装器)。
编辑:更新的代码以使用'strictNullChecks'设置
interface IExampleProps {
name: string;
otherPerson?: string;
}
/**
* Class with props with default values
*
* @class Example
* @extends {ComponentBase<IComponentBaseSubProps, {}>}
*/
export class Example extends ComponentBase<IExampleProps, {}> {
public static defaultProps: IExampleProps = {
otherPerson: "Simon",
name: "Johnny"
};
constructor(props: IExampleProps) {
super(props);
}
public render(): JSX.Element {
const person: string = this.props.otherPerson === undefined ? "" : this.props.otherPerson;
return(
<div>
<h1><small>Message by ComponentBaseSub: Hello {this.props.name} and {person} </small></h1>
</div>
);
}
}
我使用Visual Studio Code,TypeScript 2.0.3,TSLint 0.5.39没有任何问题。
更简单的是
<span>{(defaulted as string).toUpperCase()}</span>
与属性的工作方式相同。 如果Foo
需要barProp
属性但Parent
不需要并通过defaultProps
获取它,那么Parent
的render方法可以
<Foo barProp={this.props.barProp as string} />
如果您确定prop将具有默认值,则可以使用null断言类型运算符,如下所示:
render() {
const { defaulted } = this.props;
return (
<span>{defaulted!.toUpperCase()}</span>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.