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

如何在映射数组中基于styled components实现按钮独立样式控制

解决方案:结合Styled Components实现答题按钮样式逻辑

问题核心

原方案使用单一的isCorrect状态,无法区分「点击正确按钮」和「点击错误按钮」两种场景,也无法针对每个按钮的自身属性单独控制样式,导致所有按钮样式统一变化。

调整状态设计

将单一状态替换为标记答题状态的变量,用于区分当前是否已答题,以及答题的对错:

import { useState } from 'react';
import styled from 'styled-components';

// 示例答案数组
const answers = [
  { text: '选项1', isAnswerCorrect: false },
  { text: '选项2', isAnswerCorrect: true },
  { text: '选项3', isAnswerCorrect: false },
  { text: '选项4', isAnswerCorrect: false },
];

export default function Quiz() {
  // answerState: null=未答题, 'correct'=点击正确按钮, 'incorrect'=点击错误按钮
  const [answerState, setAnswerState] = useState(null);

实现点击逻辑

点击按钮时,根据按钮自身的isAnswerCorrect属性设置答题状态,同时避免重复点击:

const handleButtonClick = (isAnswerCorrect) => {
    if (answerState !== null) return;
    setAnswerState(isAnswerCorrect ? 'correct' : 'incorrect');
  };

Styled Components样式控制

给按钮组件传递answerState和自身的isAnswerCorrect属性,在样式中编写条件逻辑实现精准控制:

const AnswerButton = styled.button`
    padding: 10px 20px;
    margin: 0 10px;
    border: 2px solid #ddd;
    background: white;
    cursor: pointer;
    transition: border-color 0.3s;

    /* 禁用状态样式(可选) */
    ${({ disabled }) => disabled && `
      cursor: not-allowed;
      opacity: 0.7;
    `}

    /* 根据答题状态和自身属性设置边框颜色 */
    ${({ answerState, isAnswerCorrect }) => {
      if (answerState === 'correct') {
        // 点击正确按钮:仅当前正确按钮显示绿色边框
        return isAnswerCorrect ? 'border-color: #2ecc71;' : '';
      } else if (answerState === 'incorrect') {
        // 点击错误按钮:正确按钮绿边框,错误按钮红边框
        return isAnswerCorrect ? 'border-color: #2ecc71;' : 'border-color: #e74c3c;';
      }
      return '';
    }}
  `;

渲染按钮

遍历答案数组,给每个按钮传递必要的props:

return (
    <div>
      {answers.map((answer, idx) => (
        <AnswerButton
          key={idx}
          isAnswerCorrect={answer.isAnswerCorrect}
          answerState={answerState}
          onClick={() => handleButtonClick(answer.isAnswerCorrect)}
          disabled={answerState !== null}
        >
          {answer.text}
        </AnswerButton>
      ))}
    </div>
  );
}

效果说明

  • 未点击任何按钮时:所有按钮保持默认灰色边框
  • 点击正确按钮:仅该正确按钮变为绿色边框,其余错误按钮样式不变
  • 点击错误按钮:所有正确按钮变为绿色边框,所有错误按钮变为红色边框

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:05:18