简体   繁体   中英

How to merge state and props and then pass them as props?

I am trying to make component that will combine props and state so that the actual view only needs to worry about getting data from props. In the code below, I am trying to use the spread operator (probably incorrectly)

class CombinePropsWithStateComponent extends React.Component {
    ...snip...
    render() {
        return(<View {...props, this.state}/>);
    }
}

I don't think you can use the spread operator to combine objects inside <View /> . Even though it kind of acts like an ES2015 spread operator, it's quite hard wired to React and JSX, and only allows ...foo which is an object that gets transferred as props. If it was a "real" spread operator, the proper syntax would be {{...this.props, ...this.state}} with double curly braces.

You could try to combine props and state first, then pass along the new object:

render() {
    const newProps = {...this.props, ...this.state}
    return(<View {...newProps} />)
}

Following this logic <View {...{...this.props, ...this.state}} should work as well, but I'm not able to test this at the moment.

You should be able to combine the props and state before passing them in as props:

    const newProps = Object.assign({}, this.props, this.state)
    return(<View {...newProps} />) // Or, as a named single prop

It's worth noting that AFAIK the object spread operator is ES7 and requires some Babel flags to use.

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