我正在尝试制作将 props 和状态组合在一起的组件,以便实际视图只需要担心从 props 获取数据。 在下面的代码中,我正在尝试使用点差运算符(可能不正确)
class CombinePropsWithStateComponent extends React.Component {
...snip...
render() {
return(<View {...props, this.state}/>);
}
}
我认为你不能使用展开运算符来组合<View />
中的对象。尽管它有点像 ES2015 传播运算符,但它与 React 和 JSX 非常硬连线,并且只允许......foo,这是一个作为道具被转移的对象。如果它是一个"真正的"传播运算符,正确的语法将是{{...这个道具,...this.state}} 带有双花括号。
您可以尝试先组合 props 和状态,然后传递新对象:
render() {
const newProps = {...this.props, ...this.state}
return(<View {...newProps} />)
}
遵循此逻辑<View {...{...this.props, ...this.state}}
也应该可以工作,但我目前无法对此进行测试。
在将 props 作为 props 传入之前,您应该能够组合 props 和状态:
const newProps = Object.assign({}, this.props, this.state)
return(<View {...newProps} />) // Or, as a named single prop
值得注意的是,AFAIK 的对象传播运算符是 ES7,需要使用一些 Babel 标志。