提交后清除Redux形式 - 多个单选按钮

时间:2016-04-27 05:37:25

标签: javascript reactjs redux-form

也许我会采用这种错误方式,但我想知道是否有一种简单的方法来重置表单/取消选中所有的单选按钮?由于我要渲染的问题数量可变,我使用的是dynamic 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);

1 个答案:

答案 0 :(得分: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}>

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