![](/img/trans.png)
[英]React functional component with spread operator for props using typescript
[英]TypeScript equivalent of rest/spread props in React stateless component
我正在尝试将以下函数(从bootstrap-react
文档中添加到我的TypeScript + React项目中)添加:
function FieldGroup({ id, label, help, ...props }) {
return (
<FormGroup controlId={id}>
<ControlLabel>{label}</ControlLabel>
<FormControl {...props} />
{help && <HelpBlock>{help}</HelpBlock>}
</FormGroup>
);
}
但是,TypeScript版本<2.1不支持用作参数的ECMAScript 6的rest / spread属性。
我目前的实施是:
interface FieldGroupProps extends React.HTMLAttributes {
id?: string;
label?: string;
help?: string;
}
class FieldGroup extends React.Component<FieldGroupProps, {}> {
public render(): JSX.Element {
const rest = objectWithout(this.props, ["id", "label", "help"]);
return (
<FormGroup controlId={this.props.id}>
<ControlLabel>{this.props.label}</ControlLabel>
<FormControl {...rest} />
{this.props.help && <HelpBlock>{this.props.help}</HelpBlock>}
</FormGroup>
);
}
}
这在功能上(不是从性能角度来看)等同于ECMAScript 6版本吗? 如果我错过了某些东西或者它可以变得更优雅,那么推荐使用上述rest / spread语法的方法是什么?
在TypeScript 3中,您的第一个示例将正常工作,因此您无需将其重写为类。
如果您愿意,还可以使用FieldGroupProps
界面并将其重写为箭头功能。
const FieldGroup = ({ id, label, help, ...props }: FieldGroupProps) => <FormGroup controlId={id}>
<ControlLabel>{label}</ControlLabel>
<FormControl {...props} />
{help && <HelpBlock>{help}</HelpBlock>}
</FormGroup>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.