简体   繁体   English

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

[英]Add style from props to existing component styles in React Native

I have the following component defined:我定义了以下组件:

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

I'd like to pass a prop backgroundColor to this component.我想将道具backgroundColor传递给此组件。 But how do I extend the current styles.container to dynamically set backgroundColor ?但是如何扩展当前的styles.container以动态设置backgroundColor I've tried我试过了

<View style={
    ...styles.container, 
    backgroundColor: this.props.backgroundColor
}>...

But I get a SyntaxError when I do that...但是当我这样做时我得到了SyntaxError ...

Do it like this way: 这样做是这样的:

<View style={[styles.container, {backgroundColor: this.props.backgroundColor}]}>

React native will use StyleSheet.flatten to combine two object to be one style instance. React native将使用StyleSheet.flatten将两个对象组合成一个样式实例。

This is the same: 这是一样的:

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

Basically, React native use an object for the stylesheet.基本上,React native 使用 object 作为样式表。

To fix the above error just add {} in styles.要修复上述错误,只需在 styles 中添加 {}。

like this.像这样。

<View style={{
    ...styles.container, 
    backgroundColor: this.props.backgroundColor
}}>

For understanding purposes, the first bracket is used for evaluation and a second bracket is a stylesheet object that returns to the component.为了便于理解,第一个括号用于评估,第二个括号是返回组件的样式表 object。 now you're spreading an object (container styles) inside the main object so now it merges with the styles you provided.现在你在主 object 中传播 object(容器样式)所以现在它与你提供的 styles 合并。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM