首页 > 解决方案 > 我如何在 react-native 中覆盖 css 属性

问题描述

我已经创建了自定义按钮, <View style={styles.buttonContainer}> <AppButton title="comes in" color="yellow" /> <AppButton title="register now" color="white" /> </View>当我保存我的代码时,两个按钮都给了我相同的颜色,所以在我创建自定义按钮组件的地方我修改了背景颜色 return ( <TouchableHighlight style={[styles.button, { backgroundColor: colors[color] }]} > <Text style={styles.text}>{title}</Text> </TouchableHighlight> ); }这是有效的 ,但问题是这样我想修改marginVertical export default function AppButton({ title, color = "", marginVertical = "" }) { return ( <TouchableHighlight style={[styles.button, { backgroundColor: colors[color] ,marginVertical=[marginVertical]}]} > <Text style={styles.text}>{title}</Text> </TouchableHighlight> ); }并且在欢迎屏幕中我这样称呼它<View style={styles.buttonContainer}> <AppButton title="comes in" color="yellow" /> <AppButton title="register now" color="white" marginVertical="4"/> </View> 在此处输入图像描述

标签: react-native

解决方案


要覆盖 marginVertical 您可以像下面一样简单地传递它,而不是提供一个键并使用一个数组。

function AppButton({ title, color = '', marginVertical = 0 }) {
  return (
    <TouchableHighlight
      style={[
        styles.button,
        { backgroundColor: colors[color], marginVertical:marginVertical },
      ]}>
      <Text style={styles.text}>{title}</Text>
    </TouchableHighlight>
  );
}

此外,如果您打算使用多种样式,请使用单个样式对象并覆盖它,如下所示

function AppButton({ title, style={} }) {
  return (
    <TouchableHighlight
      style={[
        styles.button,
        style,
      ]}>
      <Text style={styles.text}>{title}</Text>
    </TouchableHighlight>
  );
}

推荐阅读