Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash-lite-preview-06-17-thinking· GoogleHugging Face LMArena Human Preference 140K

写一个按钮组件

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-sonnet-4-20250514-thinking-32k’s answer.
  1. User

    写一个按钮组件

  2. Gemini Assistant

    好的,这是一个使用 React 和 TypeScript 编写的按钮组件示例。这个组件包含了常见的属性,如点击事件、禁用状态、不同样式(variant)和尺寸(size)。

    我们将提供两种常见的样式化方法:

    1. 使用 Tailwind CSS: 适用于已经在使用 Tailwind CSS 项目中。
    2. 使用 CSS Modules (或普通 CSS): 适用于不使用 Tailwind 或需要更精细 CSS 控制的场景。

    1. React + TypeScript 按钮组件

    // src/components/Button/Button.tsx
    
    import React from 'react';
    import styles from './Button.module.css'; // 假设使用 CSS Modules
    
    // --- 定义 Props 类型 ---
    // 继承所有标准的 HTML button 属性
    interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
      /**
       * 按钮显示的内容 (文本、图标等)
       */
      children: React.ReactNode;
      /**
       * 按钮的视觉样式变体
       * @default 'primary'
       */
      variant?: 'primary' | 'secondary' | 'danger' | 'outline';
      /**
       * 按钮的尺寸
       * @default 'medium'
       */
      size?: 'small' | 'medium' | 'large';
      /**
       * 是否禁用按钮
       * @default false
       */
      disabled?: boolean;
      /**
       * 点击事件处理函数
       */
      onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;
      /**
       * 自定义 CSS 类名,用于覆盖或增强样式
       */
      className?: string;
       /**
       * 按钮类型 (用于表单)
       * @default 'button'
       */
      type?: 'button' | 'submit' | 'reset';
    }
    
    /**
     * 一个通用的按钮组件,支持多种样式和尺寸。
     */
    const Button: React.FC<ButtonProps> = ({
      children,
      variant = 'primary',
      size = 'medium',
      disabled = false,
      onClick,
      className = '',
      type = 'button',
      ...rest // 接收其他标准的 button 属性,如 aria-label 等
    }) => {
    
      // --- CSS Modules 样式构建 ---
      const buttonClasses = [
        styles.button, // 基础样式
        styles[`variant-${variant}`], // 按 variant 添加样式
        styles[`size-${size}`],     // 按 size 添加样式
        disabled ? styles.disabled : '', // 添加 disabled 样式
        className, // 用户自定义的类名
      ]
        .filter(Boolean) // 过滤掉空的字符串
        .join(' '); // 用空格连接成一个字符串
    
      return (
        <button
          type={type}
          className={buttonClasses}
          onClick={onClick}
          disabled={disabled}
          {...rest} // 传递剩余的属性
        >
          {children}
        </button>
      );
    };
    
    export default Button;
    

    2. 对应的 CSS 文件 (CSS Modules)

    /* src/components/Button/Button.module.css */
    
    /* --- 基础样式 --- */
    .button {
      display: inline-flex; /* 使用 flex 布局,方便内部元素(如图标+文本)对齐 */
      align-items: center;
      justify-content: center;
      padding: 0.5rem 1rem; /* 默认 padding */
      border: 1px solid transparent;
      border-radius: 0.375rem; /* 圆角 */
      font-size: 1rem;       /* 默认字号 */
      font-weight: 500;
      cursor: pointer;
      text-align: center;
      transition: background-color 0.2s ease, border-color 0.2s ease, color 0.2s ease, box-shadow 0.2s ease;
      text-decoration: none; /* 如果用作链接样式 */
      white-space: nowrap; /* 防止文本换行 */
    }
    
    /* --- Variant 样式 --- */
    .variant-primary {
      background-color: #007bff;
      color: white;
      border-color: #007bff;
    }
    .variant-primary:hover:not(:disabled) {
      background-color: #0056b3;
      border-color: #0056b3;
    }
    
    .variant-secondary {
      background-color: #6c757d;
      color: white;
      border-color: #6c757d;
    }
    .variant-secondary:hover:not(:disabled) {
      background-color: #5a6268;
      border-color: #5a6268;
    }
    
    .variant-danger {
      background-color: #dc3545;
      color: white;
      border-color: #dc3545;
    }
    .variant-danger:hover:not(:disabled) {
      background-color: #c82333;
      border-color: #c82333;
    }
    
    .variant-outline {
      background-color: transparent;
      color: #007bff; /* 默认 outline 颜色 */
      border-color: #007bff;
    }
    .variant-outline:hover:not(:disabled) {
      background-color: #007bff;
      color: white;
      border-color: #007bff;
    }
    /* 可以为 outline 添加其他颜色的变体 */
    /*
    .variant-outline-secondary { border-color: #6c757d; color: #6c757d; }
    .variant-outline-secondary:hover:not(:disabled) { background-color: #6c757d; color: white; }
    */
    
    
    /* --- Size 样式 --- */
    .size-small {
      padding: 0.375rem 0.75rem;
      font-size: 0.875rem;
    }
    
    .size-medium {
      padding: 0.5rem 1rem;
      font-size: 1rem;
    }
    
    .size-large {
      padding: 0.75rem 1.5rem;
      font-size: 1.125rem;
    }
    
    /* --- Disabled 样式 --- */
    .disabled {
      cursor: not-allowed;
      opacity: 0.65;
      /* 可以根据需要移除 hover 效果 */
      /* For variants */
      background-color: #ccc; /* 示例颜色 */
      border-color: #bbb;   /* 示例颜色 */
      color: #666;        /* 示例颜色 */
    }
    /* 针对 outline 的 disabled 状态 */
    .variant-outline.disabled {
      background-color: transparent;
      border-color: #ccc;
      color: #ccc;
    }
    
    /* --- Focus 状态 (可访问性) --- */
    .button:focus-visible {
      outline: 2px solid #007bff; /* 或者你设计系统中的焦点颜色 */
      outline-offset: 2px;
      box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.25); /* 模拟光晕效果 */
    }
    

    3. 如何使用这个组件

    // src/App.tsx
    import React from 'react';
    import Button from './components/Button/Button';
    import './App.css'; // 假设有一个全局的 CSS 文件
    
    function App() {
      const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
        console.log('Button clicked!', event.currentTarget);
      };
    
      return (
        <div className="app-container">
          <h1>按钮组件示例</h1>
    
          {/* 不同 Variant */}
          <div className="example-section">
            <h2>Variants</h2>
            <Button onClick={handleClick}>Primary (Default)</Button>
            <Button variant="secondary" onClick={handleClick}>Secondary</Button>
            <Button variant="danger" onClick={handleClick}>Danger</Button>
            <Button variant="outline" onClick={handleClick}>Outline</Button>
          </div>
    
          {/* 不同 Size */}
          <div className="example-section">
            <h2>Sizes</h2>
            <Button size="small" onClick={handleClick}>Small</Button>
            <Button size="medium" onClick={handleClick}>Medium</Button>
            <Button size="large" onClick={handleClick}>Large</Button>
          </div>
    
          {/* Disabled 状态 */}
          <div className="example-section">
            <h2>Disabled</h2>
            <Button disabled onClick={handleClick}>Disabled Primary</Button>
            <Button variant="secondary" disabled onClick={handleClick}>Disabled Secondary</Button>
          </div>
    
          {/* 带有自定义类名 */}
          <div className="example-section">
            <h2>Custom Class</h2>
            <Button onClick={handleClick} className="my-custom-button">
              Custom Styled Button
            </Button>
          </div>
    
          {/* 作为表单提交按钮 */}
          <form onSubmit={(e) => { e.preventDefault(); alert('Form submitted!'); }}>
             <div className="example-section">
                <h2>Form Integration</h2>
                <Button type="submit">Submit Form</Button>
                <Button type="reset">Reset Form</Button>
             </div>
          </form>
    
           {/* 包含图标 (需要额外的 CSS 或图标库) */}
           {/* <div className="example-section">
             <h2>With Icon</h2>
             <Button onClick={handleClick}><span className="icon-plus"></span> Add Item</Button>
           </div> */}
    
        </div>
      );
    }
    
    export default App;
    
    // 可以在 App.css 中添加一些基础布局样式
    /* src/App.css */
    /*
    .app-container {
      padding: 20px;
      font-family: sans-serif;
    }
    
    .example-section {
      margin-bottom: 30px;
      border-bottom: 1px solid #eee;
      padding-bottom: 20px;
    }
    
    .example-section h2 {
      margin-bottom: 15px;
      color: #333;
    }
    
    // 按钮之间的间距
    button + button {
      margin-left: 10px;
    }
    
    // 自定义按钮样式示例
    .my-custom-button {
      background-color: #28a745;
      border-radius: 20px;
      font-weight: bold;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }
    .my-custom-button:hover:not(:disabled) {
      background-color: #218838;
    }
    */
    
    

    4. 使用 Tailwind CSS 的版本 (可选)

    如果你使用 Tailwind CSS,组件代码会更简洁,样式直接写在 className 中。

    // src/components/Button/ButtonTailwind.tsx (Tailwind 版本)
    
    import React from 'react';
    
    // Props 类型与上面相同
    interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
      children: React.ReactNode;
      variant?: 'primary' | 'secondary' | 'danger' | 'outline';
      size?: 'small' | 'medium' | 'large';
      disabled?: boolean;
      onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;
      className?: string;
      type?: 'button' | 'submit' | 'reset';
    }
    
    const ButtonTailwind: React.FC<ButtonProps> = ({
      children,
      variant = 'primary',
      size = 'medium',
      disabled = false,
      onClick,
      className = '',
      type = 'button',
      ...rest
    }) => {
    
      // --- Tailwind CSS 类名映射 ---
      const baseStyles = "inline-flex items-center justify-center font-medium rounded-md transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2";
    
      // Variant 相关的样式
      const variantStyles = {
        primary: "bg-blue-600 hover:bg-blue-700 text-white focus:ring-blue-500",
        secondary: "bg-gray-600 hover:bg-gray-700 text-white focus:ring-gray-500",
        danger: "bg-red-600 hover:bg-red-700 text-white focus:ring-red-500",
        outline: "bg-transparent border border-blue-600 text-blue-600 hover:bg-blue-600 hover:text-white focus:ring-blue-500",
      };
    
      // Size 相关的样式
      const sizeStyles = {
        small: "px-3 py-2 text-sm",
        medium: "px-4 py-2 text-base",
        large: "px-6 py-3 text-lg",
      };
    
      // Disabled 相关的样式
      const disabledStyles = "opacity-65 cursor-not-allowed";
      // Tailwind 不会自动移除 hover 状态,需要手动处理或使用 group/peer 等技巧,这里简化处理
      // 对于 outline 的 disabled,需要单独调整颜色
      const disabledVariantStyles = {
          primary: "bg-gray-400 border-gray-400 text-gray-700",
          secondary: "bg-gray-400 border-gray-400 text-gray-700",
          danger: "bg-red-400 border-red-400 text-white", // 危险按钮禁用时可能颜色不同
          outline: "border-gray-400 text-gray-400 hover:bg-transparent hover:text-gray-400",
      }
    
      // --- 组合类名 ---
      const combinedClassName = [
        baseStyles,
        disabled ? disabledVariantStyles[variant] : variantStyles[variant],
        sizeStyles[size],
        disabled ? disabledStyles : '',
        className // 用户自定义的类名
      ].join(' ');
    
      return (
        <button
          type={type}
          className={combinedClassName}
          onClick={onClick}
          disabled={disabled}
          {...rest}
        >
          {children}
        </button>
      );
    };
    
    export default ButtonTailwind;
    
    // 使用时:
    // import Button from './components/Button/ButtonTailwind';
    // <Button variant="primary" size="large">Click Me</Button>
    

    说明:

    1. Props 定义: 使用 TypeScript 接口 ButtonProps 来定义组件接收的所有属性,并利用 React.ButtonHTMLAttributes<HTMLButtonElement> 继承了所有原生的 <button> 元素的属性,使组件更通用。
    2. children: 这是 React 组件的标准用法,用于包裹按钮内的内容(文本、图标等)。
    3. variant 和 size: 这些是自定义的属性,用于控制按钮的外观。我们为它们设置了默认值。
    4. disabled: 控制按钮的禁用状态。
    5. onClick: 处理按钮点击事件。
    6. className: 允许用户传入自定义的 CSS 类名,以进行额外的样式定制或覆盖。
    7. type: 指定按钮的类型,默认为 'button',也可以是 'submit' 或 'reset',常用于表单。
    8. ...rest: 使用展开语法(spread syntax)将所有未显式定义的 props(例如 aria-label, id 等)传递给底层的 <button> 元素,保持了原生行为。
    9. 样式构建:
      • CSS Modules: 通过 import styles from './Button.module.css' 引入样式文件。类名被局部作用域化,避免冲突。我们动态地组合基础类名、变体类名、尺寸类名、禁用类名和用户传入的类名。
      • Tailwind CSS: 直接在 className 字符串中写入 Tailwind 的工具类。通过对象映射和字符串拼接来动态生成类名。

    这个组件提供了一个基础但功能完善的按钮实现,你可以根据项目需求进一步扩展它,例如添加加载状态、图标支持等。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.