简体   繁体   中英

TypeScript equivalent of rest/spread props in React stateless component

I am trying to add the following function, taken from bootstrap-react documentation , to my TypeScript + React project:

function FieldGroup({ id, label, help, ...props }) {
    return (
        <FormGroup controlId={id}>
            <ControlLabel>{label}</ControlLabel>
            <FormControl {...props} />
            {help && <HelpBlock>{help}</HelpBlock>}
        </FormGroup>
    );
}

However the rest/spread properties for ECMAScript 6 used as arguments are not supported by TypeScript versions < 2.1.

My current implementation is:

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>
        );
    }
}

Is this functionally (not from a performance perspective) equivalent to the ECMAScript 6 version? If I missed something or it could be made more elegant, what is the recommended way to translate the use of the above rest/spread syntax?

In TypeScript 3, your first example will work fine so you don't need to rewrite it into a class.

If you like, you can also use your FieldGroupProps interface as well as rewriting it into an arrow function.

const FieldGroup = ({ id, label, help, ...props }: FieldGroupProps) => <FormGroup controlId={id}>
    <ControlLabel>{label}</ControlLabel>
    <FormControl {...props} />
    {help && <HelpBlock>{help}</HelpBlock>}
</FormGroup>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM