【问题标题】:How to create a button with gradient color and an icon in React Native?如何在 React Native 中创建具有渐变颜色和图标的按钮?
【发布时间】:2021-04-22 10:57:49
【问题描述】:

正如标题所说,我想问是否有一种方法可以在 React Native 中创建具有渐变色和图标的按钮?我知道没有外部库就无法添加渐变色,所以我尝试了这个:

https://www.npmjs.com/package/react-native-gradient-buttons

但是,我看不到将 Icon 作为道具添加到该库的渐变按钮的方法。答案不一定要用库,我只是想知道一种方便的方法来实现我描述的按钮。谢谢。

【问题讨论】:

    标签: css react-native


    【解决方案1】:

    您可以使用如下图标创建自己的按钮

    import { Ionicons } from '@expo/vector-icons';
    import { LinearGradient } from 'expo-linear-gradient';
    
    const GradientButton = ({ onPress, style, colors, text, renderIcon }) => {
      return (
        <TouchableOpacity onPress={onPress}>
          <LinearGradient colors={colors} style={style}>
            {renderIcon()}
            <Text style={styles.text}>{text}</Text>
          </LinearGradient>
        </TouchableOpacity>
      );
    };
    

    用法是

      <GradientButton
        onPress={() => alert('Button Pressed')}
        style={{
          padding: 15,
          alignItems: 'center',
          borderRadius: 5,
          flexDirection: 'row',
        }}
        colors={['#874f00', '#f5ba57']}
        text="Press"
        renderIcon={() => (
          <Ionicons
            name="md-checkmark-circle"
            size={20}
            color="green"
            style={{ marginHorizontal: 20 }}
          />
        )}
      />
    

    您将对按钮有更多的控制权并可以随意更改它,您可以添加更多的道具以按照您想要的方式对其进行自定义。

    您可以在此处试用演示 https://snack.expo.io/@guruparan/gradientbutton

    以上图标和渐变包为expo 您也可以使用RN Vector iconsLinear gradient

    【讨论】:

      【解决方案2】:

      在您提供的包的文档中,它显示了一个这样的示例:

           <GradientButton
                style={{ marginVertical: 8 }}
                textStyle={{ fontSize: 20 }}
                gradientBegin="#874f00"
                gradientEnd="#f5ba57"
                gradientDirection="diagonal"
                height={60}
                width={300}
                radius={15}
                impact
                impactStyle='Light'
                onPressAction={() => alert('You pressed me!')}
          >
            Gradient Button #2
          </GradientButton>
      

      也许尝试在标签之间添加你的图标而不是作为道具?

      【讨论】:

      • 其实这回答了这个问题。我试图将 Icon 和 Text 元素放在 GradientButton 标签内。它们也可以彼此相邻排列,并将它们嵌套在具有 flexDirection: 行的视图中。然而,发生的事情是在 GradientButton 标签内添加 View 元素导致 textStyle 不影响 Text,同时我尝试添加为 Text 道具的样式也不起作用。也没有找到将“flexDirection: row”添加到 GradientButton style-props 的方法,这导致了一个死锁,其中 flexDirection 或 textStyle 必须被排除在外。
      • 不确定我是否理解你的尝试。您是否尝试过将“flexDirection: row”直接添加到 GardientButton 的样式属性中?至少docs 建议它应该可以工作。
      • 出现了一个错误,因为我在 TextStyles 中使用了 textDecorationColor 而不是颜色...我现在确信您的回答会很好。最终还是选择了 TouchableOpacity / LinearGradient 组合。
      猜你喜欢
      • 1970-01-01
      • 2021-08-08
      • 2018-10-08
      • 1970-01-01
      • 2023-03-29
      • 2011-03-13
      • 2012-12-05
      • 1970-01-01
      • 2020-06-15
      相关资源
      最近更新 更多