Я хочу внедрить систему условного рендеринга в reactjs - PullRequest
0 голосов
/ 03 апреля 2020

Я хочу показать, совпадает ли значение выбранной отмеченной кнопки с ответом в базе данных, при отображении данных из базы данных у меня есть переменная с именем и значением правильного ответа.

Также я могу получить значение выбранного радиокнопки. Я хочу сделать два div на том основании, что если значение радио такое же, как правильный ответ или нет, но я не могу понять, как это сделать.

import React, { Component } from 'react';
import axios from 'axios'
import {Form,Radio,} from 'semantic-ui-react'
import 'semantic-ui-css/semantic.min.css';





export default class QuestionList extends Component {
    constructor(props){
        super(props)
        this.handleOptionChange = this.handleOptionChange.bind(this);
        this.handleFormSubmit = this.handleFormSubmit.bind(this);

        this.state = {questions:[],
          answer:''}

    }

    handleOptionChange(e){
      this.setState({
        answer: e.target.value
      });
    }

    handleFormSubmit (e) {
      e.preventDefault();

      console.log('You have selected:', this.state.answer);
    }


    componentDidMount(){
        axios.get('http://localhost:5000/question/')
        .then(respose =>{
            this.setState({questions:respose.data})
        })
        .catch(error => {
            console.log(error);
        });

    };



    questionList() {

        return this.state.questions.map(currentquestion => {

          return(
            <Form onSubmit ={this.handleFormSubmit}>
        <Form.Field>
         <h3>Q.  {currentquestion.ques}</h3>
          <h6>Correct Answer is {currentquestion.ans} </h6>
        </Form.Field>
        <Form.Field>
          <Radio
            label={currentquestion.options[0]}
            name='radioGroup'
            value ={currentquestion.options[0]}
            checked = {this.state.answer === currentquestion.options[0]}
            onChange={this.handleOptionChange}

          />
        </Form.Field>
        <Form.Field>
          <Radio
            label={currentquestion.options[1]}
            name='radioGroup'
            value ={currentquestion.options[1]}
            checked = {this.state.answer === currentquestion.options[1]}
            onChange={this.handleOptionChange}

          />
        </Form.Field>
        <Form.Field>
          <Radio
            label={currentquestion.options[2]}
            name='radioGroup'
            value = {currentquestion.options[2]}
            checked = {this.state.answer === currentquestion.options[2]}
            onChange={this.handleOptionChange}

          />
        </Form.Field>
        <Form.Field>
          <Radio
            label={currentquestion.options[3]}
            name='radioGroup'
            value={currentquestion.options[3]}
            checked = {this.state.answer === currentquestion.options[3]}
            onChange={this.handleOptionChange}

          />
        </Form.Field>

        <button type ="submit" class="ui button" >Submit Answer</button>
        <hr />

      </Form>

          );
        })
      }



  render() {
    return (
        <div>
        <h2>Questions</h2>
        <hr />
        <hr />
        <p>{ this.questionList() } </p>

      </div>
    )
  }

, но когда я пытаюсь выбрать переключатель Я не могу проверить их, что означает, что я не могу сохранить что-либо в состоянии ответа.

1 Ответ

0 голосов
/ 03 апреля 2020

in semantic-ui onChange принимает два параметра (e, значение), если вы console.log значение в вашем handlechange, вы найдете его там, так что это значение, которое вы должны поместить в ваше состояние Вы можете попробовать это на своей игровой площадке в documentation: https://react.semantic-ui.com/collections/form/#shorthand -field-control Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...