ReactJs:如何显示正确的问卷答案和总分?

时间:2018-08-18 14:29:57

标签: javascript reactjs

我是新来的反应者,我想在同一页面上安排每个问题的正确选项。同样,当问题解决后,它应显示它是否正确。最后,我需要总分。我该怎么做?谢谢您的提前帮助。

这是我到目前为止所做的。.(通常会有更多问题,但是我必须删除它们才能发布)

const questionsArray = [
  {
    question: 'When the C programming language has first appeared?',
    option1: '1970',
    option2: '1971',
    option3: '1972'
  },
  {
    question: 'When the Java programming language has first appeared?',
    option1: '1994',
    option2: '1995',
    option3: '1996'
  },
];


class QuizAppQuestion extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      currentQuestionIndex: 0,
      questions: [],
      answers: []
    };
  }

  componentDidMount() {
    this.setState({questions: questionsArray})
  }

  onChangeOption(value) {
    const {currentQuestionIndex} = this.state;
    let answers = {...this.state.answers};
    answers[currentQuestionIndex] = value;
    this.setState({answers});
  }

  handleNext() {
    let incrementCurrentQuestionIndex = this.state.currentQuestionIndex + 1;
    this.setState({currentQuestionIndex: incrementCurrentQuestionIndex});
  }

  render() {
    const {questions, currentQuestionIndex, answers} = this.state;
    if (!questions.length) {
      return <div>Loading questions...</div>
    }
    if (currentQuestionIndex >= questions.length) {
      return (<div><h3>End of the quiz</h3></div>)
    }

    const {question, option1, option2, option3} = questions[currentQuestionIndex];

    return (<div>
         <h1>Question {currentQuestionIndex + 1}</h1>
         <h4>{question}</h4>
         <label>
           <input type='radio' checked={answers[currentQuestionIndex] === option1} value={option1} onChange={(evt) => this.onChangeOption(evt.target.value)}/>
                    {option1}
         </label>
         <br/>
         <label>
           <input type='radio' checked={answers[currentQuestionIndex] === option2} value={option2} onChange={(evt) => this.onChangeOption(evt.target.value)}/>
                    {option2}
          </label>
          <br/>
          <label>
             <input type='radio' checked={answers[currentQuestionIndex] === option3} value={option3} onChange={(evt) => this.onChangeOption(evt.target.value)}/>
                    {option3}
          </label>
          <hr/>
          <button onClick={() => this.handleNext()}>Next</button>
        </div>);
  }
}

1 个答案:

答案 0 :(得分:0)

您希望创建一个包含答案的单独数组,并针对答案数组中的相应问题/答案测试所选答案。因此,您的情况如下:

the_partner.importid_SmartBambi