简体   繁体   English

如何合并状态和道具,然后将它们作为道具传递?

[英]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 /> . 我认为您不能使用传播运算符在<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. 尽管它的行为类似于ES2015传播运算符,但它与React和JSX的连接非常困难,并且仅允许... foo这是一个作为props传递的对象。 If it was a "real" spread operator, the proper syntax would be {{...this.props, ...this.state}} with double curly braces. 如果它是一个“真实的”扩展运算符,则正确的语法应为带有双花括号的{{... this.props,... this.state}}。

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. 按照此逻辑, <View {...{...this.props, ...this.state}}应该可以正常工作,但目前我无法对此进行测试。

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. 值得注意的是,对象散布运算符AFAIK是ES7,需要使用一些Babel标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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