Javascript React无状态组件中rest/spread道具的TypeScript等价物
我正在尝试将以下函数添加到我的TypeScript+react项目中,该函数取自Javascript React无状态组件中rest/spread道具的TypeScript等价物,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,我正在尝试将以下函数添加到我的TypeScript+react项目中,该函数取自bootstrap react: function FieldGroup({ id, label, help, ...props }) { return ( <FormGroup controlId={id}> <ControlLabel>{label}</ControlLabel> <FormContr
bootstrap react
:
function FieldGroup({ id, label, help, ...props }) {
return (
<FormGroup controlId={id}>
<ControlLabel>{label}</ControlLabel>
<FormControl {...props} />
{help && <HelpBlock>{help}</HelpBlock>}
</FormGroup>
);
}
函数字段组({id,label,help,…props}){
返回(
{label}
{help&&{help}
);
}
但是,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>
);
}
}
interface FieldGroupProps扩展了React.HTMLAttributes{
id?:字符串;
标签?:字符串;
帮助?:字符串;
}
类FieldGroup扩展了React.Component{
public render():JSX.Element{
const rest=objectWithout(this.props,[“id”,“label”,“help”]);
返回(
{this.props.label}
{this.props.help&&{this.props.help}
);
}
}
这在功能上(不是从性能角度)等同于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>;
constfieldgroup=({id,label,help,…props}:FieldGroupProps)=>
{label}
{help&&{help}
;
查看babe如何传输rest/spread参数。