添加课程onclick

时间:2019-10-12 13:31:25

标签: reactjs

我正在制作React测验应用程序。而且我想使将类添加到活动元素的函数有效,但是在我的代码中,它会将活动类添加到数组中的所有元素。我不知道如何只向单击的按钮添加类。请帮助我。

//...
    this.state = 
       {
          questions: [
            {
              title: "Question-1", answers:['a', 'b', 'c', 'd'],
              correct: 2,
              answered: false,
            },
            {
              title: "Question-2", answers:['a', 'b', 'c', 'd'],
              correct: 0,
              answered: false,
            }
          ], 
          score:0,
       }
       this.checkAnswer = this.checkAnswer.bind(this);
  }
  
  checkAnswer(i, j) {
    const { questions, score } = this.state;
    if (questions[i].correct === j && !questions[i].answered) {
      questions[i].answered = true;
      this.setState(
        {
          score: score + 1,
          questions,
        });
    }
     
  }
            
  render() {
    return (
      <div>
      {
          this.state.questions.map((q, i) => (
         //...
                {
                  q.answers.map((answer, j) => 
                    (
                      <button
                        className={q.answered ? 'active' : ''}
                        key={j}
                        onClick={() => {
                          this.checkAnswer(i, j);
                        }}
                      >
                        {answer}
                     //...

1 个答案:

答案 0 :(得分:0)

使用此代码,如果回答了问题,则会将活动的className添加到您的所有回答按钮中。我认为您需要将选定的属性保留在答案数组中。

questions: [
    {
        title: "Question-1", 
        answers: [
                {
                    text: "a",
                    selected: true
                },
                {
                    text: "b",
                    selected: false
                },
                {
                    text: "c",
                    selected: false
                },
                {
                    text: "d",
                    selected: false
                }
        ],
        correct: 2,
        answered: false,
    }
]

要激活所选答案的className,您的代码必须为:

q.answers.map((answer, j) =>
    (
        <button
            className={a.selected ? 'active' : ''}
            key={j}
            onClick={() => {
                this.checkAnswer(i, j);
            }}
        >
            {answer}
    ...