繁体   English   中英

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

[英]How to merge state and props and then pass them as props?

我正在尝试制作将道具和状态结合在一起的组件,以便实际视图仅需要担心从道具中获取数据。 在下面的代码中,我尝试使用传播运算符(可能不正确)

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

我认为您不能使用传播运算符在<View />合并对象。 尽管它的行为类似于ES2015传播运算符,但它与React和JSX的连接非常困难,并且仅允许... foo这是一个作为props传递的对象。 如果它是一个“真实的”扩展运算符,则正确的语法应为带有双花括号的{{... this.props,... this.state}}。

您可以尝试先将道具和状态结合起来,然后传递新对象:

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

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

在将它们作为道具传递之前,您应该能够组合道具和状态:

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

值得注意的是,对象散布运算符AFAIK是ES7,需要使用一些Babel标志。

暂无
暂无

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

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