使用`...`从现有对象创建新对象时出错:在此环境中,assign的源必须是一个对象 [英] Error when creating new object from existing one using `...`: In this environment the sources for assign MUST be an object

查看:107
本文介绍了使用`...`从现有对象创建新对象时出错:在此环境中,assign的源必须是一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my React Native app, I have a situation where one particular child of a component that I render should receive either a green or red borderColor.

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

Now, I don't want to create two separate entries in my styles for these two situations since they only differ in the borderColor property.

我的想法是从我所拥有的样式对象中获取正确的样式对象我的样式是这样的:

My idea was to derive the proper style object from the ones which I have in my styles like so:

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
  )
}

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

However, this code gives the following error:


未处理的JS异常:在此环境中,分配
的源必须是object.This错误是一个性能优化,而不是符合
规范。

Unhandled JS Exception: In this environment the sources for assign MUST be an object.This error is a performance optimization and not spec compliant.

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

Apparently the error is hit on the line where I define amountStyles. Anyone knows why this happens? Is there something wrong with my syntax? I am using the ... notation to create a new object from an existing one and add some additional properties to it.

推荐答案

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

As @PitaJ pointed out, my issue was that StyleSheet.create doesn't return a plain javascript object, so the ... operator can't be applied.

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

I only want to add a solution to my original problem as well, that was to derive two different style objects from one basic one where only one property is added.

文档 code> StyleSheet API表示方法 flatten 可用于此:

The docs for the StyleSheet API indicate that the method flatten can be used for this:

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

这篇关于使用`...`从现有对象创建新对象时出错:在此环境中,assign的源必须是一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆