0

也许我走错了路,但我想知道是否有一种简单的方法来重置表单/取消选中所有单选按钮?由于我要呈现的问题数量不定,因此我使用的是动态Redux 表单。我尝试了很多不同的方法,但都没有成功。任何指针将不胜感激。

import React, { Component }  from 'react';
import { reduxForm } from 'redux-form';
import { saveQuiz } from '../../../actions/index';

class QuestionsTrueFalseMulti extends Component{

  constructor(props) {
    super();
    this.questions = props.questions;
    this.fields = props.fields;
    this.activity_data = props.activity_data;
  }

  onSubmit(data){
    this.props.saveQuiz(data);
    this.props.dispatch(reset('dynamic'));
  }

  render() {
    const { fields, handleSubmit, questions, activity_data } = this.props;  
    return(
      <div className="component-widget true-false-multi">
        <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
          <table>
            <thead>
            <tr>
              <td></td>
              <td>True</td>
              <td>False</td>
            </tr>
            </thead>
            <tbody>
              {this.questions.map((question, i) => {
                const field = fields['q_answer_'+question.id];
                return (
                  <tr key={i}>
                    <td>{question.name}</td>
                    {question.options.map((option) => {
                      return (
                        <td key={`O_${option.id}`}>
                          <input 
                            className="css-checkbox" 
                            type="radio" 
                            name={`${question.id}_answer`} 
                            value={option.answer} 
                            id={`${question.id}_answer${option.answer}`} 
                            {...field}
                          />
                          <label htmlFor={`${question.id}_answer${option.answer}`}  className="css-label"></label>
                        </td>
                      );
                    })}
                  </tr>
                );
              })}
            </tbody>
          </table>
          <button type="submit" className="btn btn-primary">Submit</button>
        </form>
      </div>
    );
  }
}

export default reduxForm({form: 'dynamic'}, null, {saveQuiz})(QuestionsTrueFalseMulti);
4

1 回答 1

3

而你正在调用这个......

<QuestionsTrueFalseMulti
  questions={[
    {
      id: 42,
      name: 'Is redux-form awesome?',
      options: [
        { answer: true },
        { answer: false }
      ]
    },
    {
      id: 43,
      name: 'Is the dress black and gold?',
      options: [
        { answer: 'Black and gold' },
        { answer: 'Blue and grey' }
      ]
    }
  ]}
  fields={[
    'q_answer_42'
    'q_answer_43'
  ]}
/>

? 如果它没有重置,听起来你可能没有提供fields阵列。

几点观察:

  • 没有必要保存this.fields = this.props.fields
  • 您可以删除onSubmit并执行reduxForm({form: 'dynamic'}, null, {onSubmit: saveQuiz})然后<form onSubmit={handleSubmit}>

多项选择测验组件是一个非常有趣的想法。我什至可以编写一个这样做的例子。

于 2016-04-27T12:53:42.323 回答