RN组件库 - Button 组件

2024-06-23 02:36
文章标签 组件 button rn

本文主要是介绍RN组件库 - Button 组件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

从零构建 React Native 组件库,作为一个前端er~谁不想拥有一个自己的组件库呢

1、定义 Button 基本类型 type.ts

import type {StyleProp, TextStyle, ViewProps} from 'react-native';
import type {TouchableOpacityProps} from '../TouchableOpacity/type';
import type Loading from '../Loading';// 五种按钮类型
export type ButtonType =| 'primary'| 'success'| 'warning'| 'danger'| 'default';
// 四种按钮大小
export type ButtonSize = 'large' | 'small' | 'mini' | 'normal';
// 加载中组件类型
type LoadingProps = React.ComponentProps<typeof Loading>;
// 按钮的基本属性
// extends Pick的作用是:
// 继承父类型的属性和方法:通过extends关键字,子类型可以继承父类型的所有属性和方法。
// 选取父类型的特定属性:通过Pick工具类型,从父类型中选取需要的属性,并将其添加到子类型中。
export interface ButtonPropsextends Pick<ViewProps, 'style' | 'testID'>,Pick<TouchableOpacityProps,'onPress' | 'onLongPress' | 'onPressIn' | 'onPressOut'> {/*** 类型,可选值为 primary success warning danger* @default default*/type?: ButtonType;/*** 尺寸,可选值为 large small mini* @default normal*/size?: ButtonSize;/*** 按钮颜色,支持传入 linear-gradient 渐变色*/color?: string;/*** 左侧图标名称或自定义图标组件*/icon?: React.ReactNode;/*** 图标展示位置,可选值为 right* @default left*/iconPosition?: 'left' | 'right';/*** 是否为朴素按钮*/plain?: boolean;/*** 是否为方形按钮*/square?: boolean;/*** 是否为圆形按钮*/round?: boolean;/*** 是否禁用按钮*/disabled?: boolean;/*** 是否显示为加载状态*/loading?: boolean;/*** 加载状态提示文字*/loadingText?: string;/*** 加载图标类型*/loadingType?: LoadingProps['type'];/*** 加载图标大小*/loadingSize?: number;textStyle?: StyleProp<TextStyle>;children?: React.ReactNode;
}

2、动态生成样式对象style.ts

import {StyleSheet} from 'react-native';
import type {ViewStyle, TextStyle} from 'react-native';
import type {ButtonType, ButtonSize} from './type';type Params = {type: ButtonType;size: ButtonSize;plain?: boolean;
};type Styles = {button: ViewStyle;disabled: ViewStyle;plain: ViewStyle;round: ViewStyle;square: ViewStyle;text: TextStyle;
};const createStyle = (theme: DiceUI.Theme,{type, size, plain}: Params,
): Styles => {// Record 是一种高级类型操作,用于创建一个对象类型// 其中键的类型由第一个参数指定(ButtonType),值的类型由第二个参数指定(ViewStyle)const buttonTypeStyleMaps: Record<ButtonType, ViewStyle> = {default: {backgroundColor: theme.button_default_background_color,borderColor: theme.button_default_border_color,borderStyle: 'solid',borderWidth: theme.button_border_width,},danger: {backgroundColor: theme.button_danger_background_color,borderColor: theme.button_danger_border_color,borderStyle: 'solid',borderWidth: theme.button_border_width,},primary: {backgroundColor: theme.button_primary_background_color,borderColor: theme.button_primary_border_color,borderStyle: 'solid',borderWidth: theme.button_border_width,},success: {backgroundColor: theme.button_success_background_color,borderColor: theme.button_success_border_color,borderStyle: 'solid',borderWidth: theme.button_border_width,},warning: {backgroundColor: theme.button_warning_background_color,borderColor: theme.button_warning_border_color,borderStyle: 'solid',borderWidth: theme.button_border_width,},};const buttonSizeStyleMaps: Record<ButtonSize, ViewStyle> = {normal: {},small: {height: theme.button_small_height,},large: {height: theme.button_large_height,width: '100%',},mini: {height: theme.button_mini_height,},};const contentPadding: Record<ButtonSize, ViewStyle> = {normal: {paddingHorizontal: theme.button_normal_padding_horizontal,},small: {paddingHorizontal: theme.button_small_padding_horizontal,},large: {},mini: {paddingHorizontal: theme.button_mini_padding_horizontal,},};const textSizeStyleMaps: Record<ButtonSize, TextStyle> = {normal: {fontSize: theme.button_normal_font_size,},large: {fontSize: theme.button_default_font_size,},mini: {fontSize: theme.button_mini_font_size,},small: {fontSize: theme.button_small_font_size,},};const textTypeStyleMaps: Record<ButtonType, TextStyle> = {default: {color: theme.button_default_color,},danger: {color: plain? theme.button_danger_background_color: theme.button_danger_color,},primary: {color: plain? theme.button_primary_background_color: theme.button_primary_color,},success: {color: plain? theme.button_success_background_color: theme.button_success_color,},warning: {color: plain? theme.button_warning_background_color: theme.button_warning_color,},};return StyleSheet.create<Styles>({button: {alignItems: 'center',borderRadius: theme.button_border_radius,flexDirection: 'row',height: theme.button_default_height,justifyContent: 'center',overflow: 'hidden',position: 'relative',...buttonTypeStyleMaps[type],...buttonSizeStyleMaps[size],...contentPadding[size],},disabled: {opacity: theme.button_disabled_opacity,},plain: {backgroundColor: theme.button_plain_background_color,},round: {borderRadius: theme.button_round_border_radius,},square: {borderRadius: 0,},text: {...textTypeStyleMaps[type],...textSizeStyleMaps[size],},});
};export default createStyle;

3、实现 Button 组件

import React, {FC, memo} from 'react';
import {View, ViewStyle, StyleSheet, Text, TextStyle} from 'react-native';
import TouchableOpacity from '../TouchableOpacity';
import {useThemeFactory} from '../Theme';
import Loading from '../Loading';
import createStyle from './style';
import type {ButtonProps} from './type';const Button: FC<ButtonProps> = memo(props => {const {type = 'default',size = 'normal',loading,loadingText,loadingType,loadingSize,icon,iconPosition = 'left',color,plain,square,round,disabled,textStyle,children,// 对象的解构操作,在末尾使用...会将剩余的属性都收集到 rest 对象中。...rest} = props;// useThemeFactory 调用 createStyle 函数根据入参动态生成一个 StyleSheet.create<Styles> 对象const {styles} = useThemeFactory(createStyle, {type, size, plain});const text = loading ? loadingText : children;// 将属性合并到一个新的样式对象中,并返回这个新的样式对象。const textFlattenStyle = StyleSheet.flatten<TextStyle>([styles.text,!!color && {color: plain ? color : 'white'},textStyle,]);// 渲染图标const renderIcon = () => {const defaultIconSize = textFlattenStyle.fontSize;const iconColor = color ?? (textFlattenStyle.color as string);let marginStyles: ViewStyle;if (!text) {marginStyles = {};} else if (iconPosition === 'left') {marginStyles = {marginRight: 4};} else {marginStyles = {marginLeft: 4};}return (<>{icon && loading !== true && (<View style={marginStyles}>{/* React 提供的一个顶层 API,用于检查某个值是否为 React 元素 */}{React.isValidElement(icon)? React.cloneElement(icon as React.ReactElement<any, string>, {size: defaultIconSize,color: iconColor,}): icon}</View>)}{loading && (<Loading// ?? 可选链操作符,如果 loadingSize 为 null 或 undefined ,就使用 defaultIconSize 作为默认值size={loadingSize ?? defaultIconSize}type={loadingType}color={iconColor}style={marginStyles}/>)}</>);};// 渲染文本const renderText = () => {if (!text) {return null;}return (<Text selectable={false} numberOfLines={1} style={textFlattenStyle}>{text}</Text>);};return (<TouchableOpacity{...rest}disabled={disabled}activeOpacity={0.6}style={[styles.button,props.style,plain && styles.plain,round && styles.round,square && styles.square,disabled && styles.disabled,// !!是一种类型转换的方法,它可以将一个值转换为布尔类型的true或false!!color && {borderColor: color},!!color && !plain && {backgroundColor: color},]}>{iconPosition === 'left' && renderIcon()}{renderText()}{iconPosition === 'right' && renderIcon()}</TouchableOpacity>);
});export default Button;

4、对外导出 Botton 组件及其类型文件

import Button from './Button';export default Button;
export {Button};
export type {ButtonProps, ButtonSize, ButtonType} from './type';

5、主题样式

动态生成样式对象调用函数

import {useMemo} from 'react';
import {createTheming} from '@callstack/react-theme-provider';
import type {StyleSheet} from 'react-native';
import {defaultTheme} from '../styles';
// 创建主题对象:调用 createTheming 函数并传入一个默认主题作为参数
export const {ThemeProvider, withTheme, useTheme} = createTheming<DiceUI.Theme>(defaultTheme as DiceUI.Theme,
);type ThemeFactoryCallBack<T extends StyleSheet.NamedStyles<T>> = {styles: T;theme: DiceUI.Theme;
};export function useThemeFactory<T extends StyleSheet.NamedStyles<T>, P>(fun: (theme: DiceUI.Theme, ...extra: P[]) => T,...params: P[]
): ThemeFactoryCallBack<T> {// 钩子,用于在函数组件中获取当前的主题const theme = useTheme();const styles = useMemo(() => fun(theme, ...params), [fun, theme, params]);return {styles, theme};
}export default {ThemeProvider,withTheme,useTheme,useThemeFactory,
};

6、Demo 演示

在这里插入图片描述

这篇关于RN组件库 - Button 组件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1086061

相关文章

C++ RabbitMq消息队列组件详解

《C++RabbitMq消息队列组件详解》:本文主要介绍C++RabbitMq消息队列组件的相关知识,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. RabbitMq介绍2. 安装RabbitMQ3. 安装 RabbitMQ 的 C++客户端库4. A

Kotlin Compose Button 实现长按监听并实现动画效果(完整代码)

《KotlinComposeButton实现长按监听并实现动画效果(完整代码)》想要实现长按按钮开始录音,松开发送的功能,因此为了实现这些功能就需要自己写一个Button来解决问题,下面小编给大... 目录Button 实现原理1. Surface 的作用(关键)2. InteractionSource3.

PyQt6中QMainWindow组件的使用详解

《PyQt6中QMainWindow组件的使用详解》QMainWindow是PyQt6中用于构建桌面应用程序的基础组件,本文主要介绍了PyQt6中QMainWindow组件的使用,具有一定的参考价值,... 目录1. QMainWindow 组php件概述2. 使用 QMainWindow3. QMainW

Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案

《Vue3组件中getCurrentInstance()获取App实例,但是返回null的解决方案》:本文主要介绍Vue3组件中getCurrentInstance()获取App实例,但是返回nu... 目录vue3组件中getCurrentInstajavascriptnce()获取App实例,但是返回n

SpringQuartz定时任务核心组件JobDetail与Trigger配置

《SpringQuartz定时任务核心组件JobDetail与Trigger配置》Spring框架与Quartz调度器的集成提供了强大而灵活的定时任务解决方案,本文主要介绍了SpringQuartz定... 目录引言一、Spring Quartz基础架构1.1 核心组件概述1.2 Spring集成优势二、J

Vue中组件之间传值的六种方式(完整版)

《Vue中组件之间传值的六种方式(完整版)》组件是vue.js最强大的功能之一,而组件实例的作用域是相互独立的,这就意味着不同组件之间的数据无法相互引用,针对不同的使用场景,如何选择行之有效的通信方式... 目录前言方法一、props/$emit1.父组件向子组件传值2.子组件向父组件传值(通过事件形式)方

Spring组件初始化扩展点BeanPostProcessor的作用详解

《Spring组件初始化扩展点BeanPostProcessor的作用详解》本文通过实战案例和常见应用场景详细介绍了BeanPostProcessor的使用,并强调了其在Spring扩展中的重要性,感... 目录一、概述二、BeanPostProcessor的作用三、核心方法解析1、postProcessB

kotlin中的行为组件及高级用法

《kotlin中的行为组件及高级用法》Jetpack中的四大行为组件:WorkManager、DataBinding、Coroutines和Lifecycle,分别解决了后台任务调度、数据驱动UI、异... 目录WorkManager工作原理最佳实践Data Binding工作原理进阶技巧Coroutine

Vue项目的甘特图组件之dhtmlx-gantt使用教程和实现效果展示(推荐)

《Vue项目的甘特图组件之dhtmlx-gantt使用教程和实现效果展示(推荐)》文章介绍了如何使用dhtmlx-gantt组件来实现公司的甘特图需求,并提供了一个简单的Vue组件示例,文章还分享了一... 目录一、首先 npm 安装插件二、创建一个vue组件三、业务页面内 引用自定义组件:四、dhtmlx

Vue ElementUI中Upload组件批量上传的实现代码

《VueElementUI中Upload组件批量上传的实现代码》ElementUI中Upload组件批量上传通过获取upload组件的DOM、文件、上传地址和数据,封装uploadFiles方法,使... ElementUI中Upload组件如何批量上传首先就是upload组件 <el-upl