在React Native中更新组件样式的元素

时间:2018-01-09 12:52:36

标签: javascript reactjs react-native babeljs jsx

我有一个名为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' }}>

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

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

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

答案 1 :(得分:0)

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

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

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

Here是默认情况下反应原生样式的文档。