首页 > 解决方案 > 添加类 onclick

问题描述

我正在制作反应测验应用程序。而且我想创建将类添加到活动元素的函数,但在我的代码中,它将活动类添加到数组中的所有元素。我不知道如何仅将类添加到单击的按钮。请帮帮我。

//...
    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}
                     //...

标签: reactjs

解决方案


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

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}
    ...


推荐阅读