You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native自定义Button组件设置props默认值的实现方法

实现方案

代码优化说明

  • 移除冗余的useState和useEffect逻辑:props本身是响应式的,父组件传值变化时会自动触发组件重渲染,不需要手动同步到本地state
  • 解构props时直接设置默认值,写法更简洁,无需额外的空值判断
  • 修复了原代码中默认颜色的非法字符问题,示例改为合法的暗粉色#8a4a5a
  • 补充了rounded属性的样式实现逻辑,同时将点击事件改为可自定义,更符合通用组件的设计逻辑
import * as React from 'react';
import { StyleSheet } from 'react-native';
import { Button } from 'react-native-paper';

// 解构props时直接设置默认值
const CustomButton = ({
  title,
  color = '#8a4a5a',
  icon,
  rounded = false,
  disabled = false,
  onPress = () => console.log('Pressed')
}) => {
  return (
    <Button
      icon={icon}
      mode="contained"
      color={color}
      onPress={onPress}
      disabled={disabled}
      style={rounded ? styles.roundedButton : {}}
    >
      {title}
    </Button>
  );
};

export default CustomButton;

const styles = StyleSheet.create({
  roundedButton: {
    borderRadius: 999
  }
});

补充说明

如果需要兼容更旧的React版本,也可以用defaultProps设置默认值:

CustomButton.defaultProps = {
  color: '#8a4a5a',
  rounded: false,
  disabled: false,
  onPress: () => console.log('Pressed')
};

组件使用示例:

// 用默认配置的按钮
<CustomButton title="默认按钮" />
// 自定义颜色+圆角的按钮
<CustomButton title="蓝色按钮" color="#2196F3" rounded />
// 带图标+禁用状态的按钮
<CustomButton title="禁用按钮" icon="camera" disabled />

内容的提问来源于stack exchange,提问作者Trinkflasche93

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 04:00:01