创建具有复杂样式的圆形 React Native 组件

问题描述 投票:0回答:1

我一直在深入研究 React Native 的世界。这个领域完全陌生。

并尝试创建一个按钮组件。其中按钮是圆形的,并且具有特定的颜色,标题将通过参数发送给它。

我想做的复杂的事情是尝试为按钮实现一种内部线性效果,正如附图所示,它看起来像一个细小的内部圆圈。

请查找附图作为我想要实现的目标的示例:

Setting Image

我尝试过以下代码:

import React from 'react';
import { TouchableOpacity, Text, StyleSheet } from 'react-native';

const HomeButton = ({ title, color }) => {
  return (
    <TouchableOpacity style={[styles.button, { backgroundColor: color }]}>
      <Text style={styles.title}>{title}</Text>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  button: {
    width: 100,
    height: 100,
    borderRadius: 100,
    justifyContent: 'center',
    alignItems: 'center',
    elevation: 5,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.5,
  },
  title: {
    fontSize: 20,
    color: '#fff',
    textAlign: 'center',
  },
});

export default HomeButton;

这实际上创建了一个圆形按钮,但颜色非常静态。

还尝试安装和使用以下内容只是为了解决单一颜色问题,但仍然不起作用:

npm 安装反应原生线性梯度

代码变成这样的:

const HomeButton = ({ title, colors }) => {
  return (
    <TouchableOpacity style={styles.button}>
      <LinearGradient
        colors={colors}
        style={styles.gradient}
      >
        <View style={styles.innerCircle} />
        <Text style={styles.title}>{title}</Text>
      </LinearGradient>
    </TouchableOpacity>
  );
};

这个设计真的可行吗?请问有什么帮助吗?

react-native
1个回答
0
投票

如果您有一个非常棘手的组件(如您提供的示例中所示),您可以尝试将其下载为图像并按以下方式创建按钮:

interface Props extends TouchableOpacityProps {
  title: string;
}

const HomeButton: React.FC<Props> = ({title, style, ...restProps}) => (
  <TouchableOpacity style={[{alignSelf: 'center'}, style]} {...restProps}>
    <ImageBackground
      source={require('@assets/images/button.jpeg')}
      style={{justifyContent: 'center', alignItems: 'center', width: 100, height: 100, padding: 10}}>
      <Text style={{color: 'white', textDecorationLine: 'underline', flexWrap: 'wrap'}}>{title}</Text>
    </ImageBackground>
 </TouchableOpacity>
)

Gif 代码片段中的工作原理示例

© www.soinside.com 2019 - 2024. All rights reserved.