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

时间:2018-07-11 09:32:06

标签: react-native react-native-android react-native-ios expo native-base

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

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

但是不记得正确的语法如何。现在不工作。该代码如何固定?

2 个答案:

答案 0 :(得分:4)

您有几种选择。

选项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>

答案 1 :(得分:0)

您可以通过传递一系列样式来实现

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