Erw*_*yer 9 javascript typescript reactjs
我正在尝试将以下函数从bootstrap-react 文档中添加到我的TypeScript + React项目中:
function FieldGroup({ id, label, help, ...props }) {
return (
<FormGroup controlId={id}>
<ControlLabel>{label}</ControlLabel>
<FormControl {...props} />
{help && <HelpBlock>{help}</HelpBlock>}
</FormGroup>
);
}
Run Code Online (Sandbox Code Playgroud)
但是,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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
这在功能上(不是从性能角度来看)等同于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>;
Run Code Online (Sandbox Code Playgroud)