我正在创建一个接受可选道具的简单组件,但也接受任意道具传递给它的子组件,但是我不能让这个组合很好地一起玩。我从这里修改了样本作为例子:Typescript3 Release Notes
import React from 'react';
export interface Props {
name: string;
[id: string]: any; // <-- Added to allow acceptance of arbitrary props
}
export class Greet extends React.Component<Props> {
render() {
const { name, ...divProps } = this.props;
return <div {...divProps}>Hello {name.toUpperCase()}!</div>;
}
static defaultProps = { name: 'world' };
}
用法:
<Greet />
一旦我添加了具有任意道具的选项,我就会收到以下错误
Property 'name' is missing in type '{}' but required in type 'Readonly<Props>'.
我的问题是:
1)有没有任何已知的方法来接受任意道具并使defaultProps工作?
2)这是一个好的(有更好的?)方式接受任意道具?
如果您为内部组件定义了道具,则可以将它们交叉(&)在一起,这样您就可以在所有道具上保持类型安全。
type Props = {
name: string;
}
type InnerCompProps = {
color: string,
}
const InnerComp = (props: InnerCompProps) => (<div> the color is { props.color} </div>);
export class Greet extends React.Component<Props & InnerCompProps> {
static defaultProps = { name: 'world' };
render() {
const { name, ...rest } = this.props;
return <InnerComp {...rest} />;
}
}