【问题标题】:Add style from props to existing component styles in React Native在 React Native 中将样式从 props 添加到现有组件样式
【发布时间】:2018-07-01 20:57:38
【问题描述】:

我定义了以下组件:

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

我想将一个 prop backgroundColor 传递给这个组件。但是如何扩展当前的styles.container 以动态设置backgroundColor?我试过了

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

但是当我这样做时,我会得到一个SyntaxError...

【问题讨论】:

    标签: javascript reactjs react-native ecmascript-6


    【解决方案1】:

    这样做:

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

    React Native 将使用 StyleSheet.flatten 将两个对象组合为一个样式实例。

    这是一样的:

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

    【讨论】:

    • 太棒了!非常感谢:)
    • 我很高兴它有帮助。 @Tiwaz89
    【解决方案2】:

    基本上,React native 使用一个对象作为样式表。

    要修复上述错误,只需在样式中添加 {}。

    像这样。

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

    为了便于理解,第一个括号用于评估 第二个括号是返回组件的样式表对象。现在您正在主对象内传播一个对象(容器样式),因此现在它与您提供的样式合并。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      • 2018-12-13
      相关资源
      最近更新 更多