使用`...`从现有对象创建新对象时出错:在此环境中,assign的源必须是一个对象

时间:2016-05-04 06:47:25

标签: javascript reactjs react-native

在我的React Native应用程序中,我有一种情况,即我render组件中的一个特定子项应该接收绿色或红色borderColor

现在,我不想在我的styles中针对这两种情况创建两个单独的条目,因为它们仅在borderColor属性中有所不同。

我的想法是从我styles中的那些样式对象中获取正确的样式对象:

const styles = StyleSheet.create({
  amountSection: {
    borderWidth: 1,
    flex: 1,
    flexDirection: 'row',
    borderRadius: 3
  }
})

render() {
  const amountBorderColor = this.state.isClaim ? 'green' : 'red'
  const amountStyles = {
    ...styles.amountSection,
    borderColor: amountBorderColor
  }

  return (
    // ... apply amountStyles at appropriate component
  )
}

但是,此代码会出现以下错误:

  

未处理的JS异常:在此环境中为assign提供源   必须是一个对象。这个错误是性能优化而不是   符合规范。

显然,在我定义amountStyles的行上会出现错误。谁知道为什么会这样?我的语法有问题吗?我使用...表示法从现有对象创建一个新对象,并为其添加一些其他属性。

2 个答案:

答案 0 :(得分:73)

正如@PitaJ指出的那样,我的问题是StyleSheet.create没有返回普通的javascript对象,因此...运算符无法应用。

我只想为我原来的问题添加一个解决方案,那就是从一个只添加一个属性的基本方法中派生两个不同的样式对象。

StyleSheet API的docs表示方法flatten可用于此:

const amountBorderColor = this.state.isClaim ? 'green' : 'red'
const amountStyles = StyleSheet.flatten([styles.amountSection, {borderColor: amountBorderColor}])

答案 1 :(得分:6)

工厂函数似乎不返回具有您需要的属性的JavaScript对象,并且环境不希望将扩展运算符应用于未定义的值。如果要使用它,请将传递给该函数的对象拉出到另一个变量中。