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

nbu*_*urk 34 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
  )
}
Run Code Online (Sandbox Code Playgroud)

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

未处理的JS异常:在此环境中,assign的源必须是一个对象.此错误是性能优化而不是规范兼容.

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

nbu*_*urk 73

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

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

文档StyleSheetAPI表明,该方法flatten可以用于这样的:

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

  • 您也可以直接在JSX元素的`style`属性上使用它,如下所示:`<View style = {[styles.amountSection,{borderColor:this.state.isClaim?'green':'red'}]}> </ View>` (3认同)

Pit*_*taJ 6

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