如何为一个元素添加除样式对象之外的额外样式?

How to add extra style besides styles object for one element?

几个月前我看到了一个例子,其中向同一个元素添加了额外的样式,如下所示:

<Button style={ styles.button && backgroundColor: '#222222'}> 
<Text> Learn more </Text>
</Button>

但不记得正确的语法是怎样的。现在不行了。如何修复此代码?

你有几个选择。

选项 1:

您可以spread the object并在后面添加您想要的。

<Button style={{ ...styles.button, backgroundColor: '#222222'}}> 
  <Text> Learn more </Text>
</Button>

选项 2:

您可以使用 Object.assign() 克隆并向您的对象添加更多属性。

<Button style={Object.assign({}, styles.button, { backgroundColor: '#222222'})}> 
  <Text> Learn more </Text>
</Button>

选项 3:

style prop 可以有一个对象数组。

<Button style={[styles.button, { backgroundColor: '#222222'}]}> 
  <Text> Learn more </Text>
</Button>

您可以通过传递样式数组来实现

<Button style={[styles.button, { backgroundColor: 'white' }]} />