Saat ini, di halaman kuis saya, semua opsi jawaban diwarnai saat diklik. Namun, hanya opsi jawaban tunggal yang harus diwarnai ulang sesuai dengan kebenarannya. Data diambil dari data.json ...

0
Christian Zintel 17 Juni 2021, 22:05

2 jawaban

Jawaban Terbaik

Anda dapat melakukan ini bahwa:

export default function QuizCard({ title, scenario, question, answers }) {
  const [bgColor, setBgColor] = useState('gray')
  const [selectAnswer, setSelectAnswer] = useState(null)
  const handleAnswerClick = (isCorrect, answer) => {
    if (isCorrect === true) {
      setBgColor('green')
    } else {
      setBgColor('red')
    }
    setSelectAnswer(answer)
  }

  return (
    <>
      <Card bgColor={bgColor}>
        <h2>{title}</h2>
        <p>{scenario}</p>
        <h3>{question}</h3>
        <AnswerSection>
          {answers.map(answer => (
            <AnswerButton
              key={answer.answerText}
              onClick={() =>
                handleAnswerClick(answer.isCorrect, answer.answerText)
              }
              isCorrect={answer.isCorrect}
              bgColor={answer.answerText === selectAnswer ? bgColor : 'gray'} // assign bgColor in state only to the right answer and for others use gray as default
            >
              {answer.answerText}
            </AnswerButton>
          ))}
        </AnswerSection>
      </Card>
    </>
  )
}
0
Krzysztof B. 17 Juni 2021, 21:48

Anda mengatur 'bgColor' untuk semua tombol jawaban. Sebaliknya Anda harus mengatur bgColor hanya untuk jawaban yang benar untuk mewarnai saja. Sedikit modifikasi dalam logika bgColor harus melakukannya.

export default function QuizCard({ title, scenario, question, answers }) {
  const [bgColor, setBgColor] = useState('gray')
  function handleAnswerClick(isCorrect) {
    if (isCorrect === true) {
      setBgColor('green')
    } else {
      setBgColor('red')
    }
  }
  return (
    <>
      <Card bgColor={bgColor}>
        <h2>{title}</h2>
        <p>{scenario}</p>
        <h3>{question}</h3>
        <AnswerSection>
          {answers.map((answer => (
            <AnswerButton
              key={answer.answerText}
              onClick={() => handleAnswerClick(answer.isCorrect)}
              isCorrect={answer.isCorrect}
              bgColor={answer.isCorrect ? bgColor : 'gray'} // assign bgColor in state only to the right answer and for others use gray as default
            >
              {answer.answerText}
            </AnswerButton>
          ))}
        </AnswerSection>
      </Card>
0
random_user 17 Juni 2021, 20:38