条件按钮 True 和 False React

Conditional Buttons True and False React

我认为错误可能出在这里...

{options.map((option) => (
          <button
            key={option}
            className={`${myAnswer === option
                ? "true"
                : myAnswer !== option
                ? "button"
                : "false"
            }`}
            onClick={() => this.checkAnswer(option)}
          >
            {option}
          </button>
        ))}

我如何确保当用户点击正确答案时 True class(出现)以及当他点击错误答案时 False class 出现在其他按钮上。是否可以在第一次点击后将按钮禁用,从而无法更改答案?

您可以像这样创建一个辅助函数:

const isAnswerCorrect = option => option === myAnswer;

...

{options.map(option => (
    <button
       key={option}
       className={isAnswerCorrect(option) ? 'correct' : 'not-correct'}
       onClick={() => this.checkAnswer(option)}
    >
        {option}
    </button>
))}

Would it be possible after clicking the first time to leave the buttons disabled, so that it is impossible to change the answer?

是的,我们可以通过不同的方式禁用这些操作。在下面的示例中,我使用 isSubmitted 来了解是否在单击答案时执行操作。我们也可以禁用 css

const { useState } = React;

const data = {
  question: "Dummy Question?",
  answers: ["A", "B", "C", "D"],
  correctAnswer: "B"
}

const Quiz = () => {
  const [selectedAnswer, setSelectedAnswer] = useState("");
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isError, setIsError] = useState(false);
    
  const onSelectAnswer = answer => {
    if(isSubmitted) return;

    setIsSubmitted(true);
    setSelectedAnswer(answer);
    setIsError(data.correctAnswer !== answer);
  }
  
  const getAnswerClass = (answer) => {
    if(!isSubmitted) {  
      return "";
    } else if(data.correctAnswer === answer) {
      return "correct";
    }
    return isError ? "incorrect": "";
  }
  
  return (
    <div>
      <h3>{data.question}</h3>
      {data.answers.map(answer => (
        <p key={answer} 
          className={getAnswerClass(answer)}
          onClick={() => { onSelectAnswer(answer)}}
        >
          {answer}
        </p>
      ))}
    </div>
  )
}

ReactDOM.render(<Quiz />, document.getElementById("react"));
p {
  border: 1px solid lightgrey;
  padding: 20px;
}

.correct {
  background: #5aad5a;
}

.incorrect {
  background: #fa7f7f;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

<div id="react"></div>

在这里,为了简单起见,我只使用了一个问题。但这可以根据您的要求进行扩展。