在React Native中将props的样式添加到现有的组件样式

5 javascript ecmascript-6 reactjs react-native

我定义了以下组件:

import React, { Component } from 'react';
import { StyleSheet, TouchableOpacity, View, Text } from 'react-native';

export default class Button extends Component {
  render() {
    return (
      <TouchableOpacity onPress={() => this.props.onPress}>
        <View style={styles.container}>
          <Text
            style={{
              color: this.props.foregroundColor,
            }}
          >
            {this.props.title}
          </Text>
        </View>
      </TouchableOpacity>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    paddingTop: 15,
    paddingBottom: 15,
    paddingRight: 20,
    paddingLeft: 20
  },
});
Run Code Online (Sandbox Code Playgroud)

我想把道具backgroundColor传给这个组件.但是如何将电流扩展styles.container到动态设置backgroundColor?我试过了

<View style={
    ...styles.container, 
    backgroundColor: this.props.backgroundColor
}>...
Run Code Online (Sandbox Code Playgroud)

但是,SyntaxError当我这样做时,我得到了...

Tom*_*Tom 17

这样做是这样的:

<View style={[styles.container, {backgroundColor: this.props.backgroundColor}]}>
Run Code Online (Sandbox Code Playgroud)

React native将使用StyleSheet.flatten将两个对象组合成一个样式实例.

这是一样的:

const newStyle = StyleSheet.flatten([
    styles.container,
    {backgroundColor: this.props.backgroundColor},
]);
Run Code Online (Sandbox Code Playgroud)