【问题标题】:Updating an element of a components style in React Native [duplicate]在 React Native 中更新组件样式的元素
【发布时间】:2018-01-09 12:52:35
【问题描述】:

我有一个名为 CardSection 的自定义组件

import React from 'react';
import { View } from 'react-native';

const CardSection = (props) => {
  return (
    <View style={styles.containerStyle}>
      {props.children}
    </View>
  );
};

const styles = {
  containerStyle: {
    borderBottomWidth: 1,
    padding: 5,
    backgroundColor: '#fff',
    justifyContent: 'flex-start',
    flexDirection: 'row',
    borderColor: '#ddd',
    position: 'relative'
  }
};

export { CardSection };

当我从另一个类实例化这个组件时,我想更新其中一个样式元素,而其他元素保持不变。下面的代码只会更新 justifyContent 元素。

  <CardSection style={{ justifyContent: 'space-between' }}>

我目前的解决方案似乎不起作用,我想避免重复元素,只需更改其中一个样式元素。

【问题讨论】:

    标签: javascript reactjs react-native babeljs jsx


    【解决方案1】:

    您可以执行以下操作:

    //destruct props
    const CardSection = ({ style, children }) => {
      return (
        // prop 'style' overrides standard containerStyle
        <View style={[styles.containerStyle, style]}>
          {children}
        </View>
      );
    };
    

    【讨论】:

      【解决方案2】:

      如果将数组传递给styles,则可以合并样式:

      const CardSection = (props) => {
        return (
          <View style={[styles.containerStyle, props.style]}>
            {props.children}
          </View>
        );
      };
      

      它们从左到右“级联”,这意味着数组中后面的样式会覆盖前面的样式。

      Here 是 react-native 默认样式的文档。

      【讨论】:

        猜你喜欢
        • 2021-12-14
        • 1970-01-01
        • 1970-01-01
        • 2019-02-14
        • 1970-01-01
        • 2023-03-22
        • 2018-02-05
        • 1970-01-01
        • 2018-03-18
        相关资源
        最近更新 更多