简体   繁体   English

如何在reactjs中将表单单选按钮重置为未选中?

[英]How to reset form radio buttons to unchecked in reactjs?

I have made 4 radio buttons for 1 question.我为 1 个问题制作了 4 个单选按钮。 I have made 2 buttons submit and clear input.我已经提交了 2 个按钮并清除了输入。 When I submit the form after clicking on clear input it does not clear the checked buttons to unchecked how can I do that using reset function ?当我在单击清除输入后提交表单时,它不会清除选中的按钮以取消选中我如何使用reset功能来做到这一点?

contactform.js:联系方式.js:

import React, { Component } from 'react';

class ContactForm extends Component {
  constructor(props){
    super(props);
    this.state = {
        age:'',
        gender:'',
        health:'',
        name:'',
        email:'',
        info:'',
        fitness:''
    };
  } 

setAge(checkedValue){
    console.log(checkedValue);
    this.setState({
        age:checkedValue
    })
  }

setGender(checkedValue){
    console.log(checkedValue);
    this.setState({
        gender:checkedValue
    })
  }

  onChangeTextBoxGender(event){
  this.setState({gender: event.target.value})
  }

 savedata(age, gender, health, name, email, info, fitness){
        let newcontent = contentref.push();
        newcontent.set({
            age:this.state.age,
            gender:this.state.gender,
            health:this.state.health,
            name:this.state.name,
            email:this.state.email,
            info:this.state.info,
            fitness:this.state.fitness
        });
  }

  reset(){
    this.setState({
      age:'',
      gender:''
    })
  }

 render() {

    return (
      <div>

        <div id="center">
          <form>

              <div className="form-group">
                <div className="col-sm-offset-2 col-sm-10">
                  <h3>[Test]Contact us Survey Form</h3>  
                </div>
              </div>

            <div id="agegroup" >
              <div className="form-group">
                <div className="col-sm-offset-2 col-sm-10">
                  <h4>What is your age group?</h4>  
                </div>
              </div>

              <div className="form-group">
                <div className="col-sm-offset-2 col-sm-10">
                  <div className="radio">
                    <label><input type="radio" name="age" onChange={this.setAge.bind(this,'>=25 yrs')}/> >=25 yrs</label>
                  </div>
                </div>
              </div>
              <div className="form-group">
                <div className="col-sm-offset-2 col-sm-10">
                  <div className="radio">
                    <label><input type="radio" name="age"  onChange={this.setAge.bind(this,'26-35 yrs')}/> 26-35 yrs</label>
                  </div>
                </div>
              </div>
              <div className="form-group">
                <div className="col-sm-offset-2 col-sm-10">
                  <div className="radio">
                    <label><input type="radio" name="age" onChange={this.setAge.bind(this,'36-50 yrs')}/> 36-50 yrs</label>
                  </div>
                </div>
              </div>
              <div className="form-group">
                <div className="col-sm-offset-2 col-sm-10">
                  <div className="radio">
                    <label><input type="radio" name="age" onChange={this.setAge.bind(this,'>50 yrs')}/> >50 yrs</label>
                  </div>
                </div>
              </div>
            </div>


            <div id="gender">
              <div className="form-group">
                <div className="col-sm-offset-2 col-sm-10">
                  <h4>What is your gender?</h4>  
                </div>
              </div>

              <div className="form-group">
                <div className="col-sm-offset-2 col-sm-10">
                  <div className="radio">
                    <label><input type="radio" name="gender" onChange={this.setGender.bind(this,'Female')}/> Female</label>
                  </div>
                </div>
              </div>
              <div className="form-group">
                <div className="col-sm-offset-2 col-sm-10">
                  <div className="radio">
                    <label><input type="radio" name="gender" onChange={this.setGender.bind(this,'Male')}/> Male</label>
                  </div>
                </div>
              </div>
              <div className="form-group">
                <div className="col-sm-offset-2 col-sm-10">
                  <div className="radio">
                    <label><input type="radio" name="gender" onChange={this.setGender.bind(this,'Prefer not to say')}/> Prefer not to say</label>
                  </div>
                </div>
              </div>

              <div className="form-group">
                <div className="col-sm-offset-2 col-sm-10">
                  <div className="radio">
                    <label><input type="radio" name="gender" onChange={this.setGender.bind(this,-1)}/>Other</label>
                    <input type="text" class="form-inline" id="other1" onChange={this.onChangeTextBoxGender.bind(this)}/>
                  </div>
                </div>
              </div>
            </div>

              <button type="button" class="btn btn-success" onClick={this.savedata.bind(this)}>Submit</button>
              <button type="button" class="btn btn-danger">Clear input</button>

          </form>
        </div>

      </div>
    );
  }
}

export default ContactForm;

See screenshots:看截图:

在此处输入图片说明

在此处输入图片说明

Give a checked attribute for you radio button.为您的单选按钮提供一个选中的属性。 Change改变

<label>
  <input 
    type="radio" 
    name="age" 
    onChange={this.setAge.bind(this,'>=25 yrs')} /> 
  {' '}      
  >=25 yrs
</label>

to

<label>
  <input 
    type="radio" 
    name="age" 
    checked={(this.state.age == '>=25 yrs')} 
    onChange={this.setAge.bind(this,'>=25 yrs')}/> 
  >=25 yrs
</label>

you can control what is selected using the state, below find and example (btw, it is not a good practice generate functions inside the render function because it will cause unnecessary rerenders)您可以在 find 和 example 下方使用 state 控制选择的内容(顺便说一句,在渲染函数中生成函数不是一个好习惯,因为它会导致不必要的重新渲染)

class App extends React.Component {
  state = {
    selectedValue : ''
  }

  optionSelected = (e) => {
    console.log(e.target.value)
    this.setState({
      selectedValue : e.target.value
    })
  }

  reset = (e) => {
    this.setState({
      selectedValue : ''
    })
  }

  render () {
    const { selectedValue } = this.state;
    return (
      <div>
        <div>
         <input 
            type="radio" 
            name="age" value="A" 
            onChange={this.optionSelected}
            checked={selectedValue === 'A'}/> A
        </div>
        <div>
         <input 
            type="radio" 
            name="age" 
            value="B" 
            onChange={this.optionSelected}
            checked={selectedValue === 'B'}/> B
        </div>
        <div>
         <input 
            type="radio" 
            name="age" 
            value="C" 
            onChange={this.optionSelected}
            checked={selectedValue === 'C'}/> C
        </div>

        <button onClick={this.reset}>reset</button>
      </div>
    );
  }
}

ReactDOM.render(<App/>, document.querySelector('#root'))

Demo演示

You are triggering a onChange handler, updating the state correctly, but you aren't actually controlling the components with this data.您正在触发 onChange 处理程序,正确更新state ,但您实际上并未使用此数据控制组件。 Here's an in-depth guide from react about Uncontrolled Components , and the recommended approach, Controlled Components in Forms.这是一份来自 react 的深入指南,关于不受控制的组件,以及推荐的方法,表单中的受控组件

In your component, you need to manually set the props checked of each radio input based on the value of this.state .在您的组件中,您需要根据this.state的值手动设置每个无线电输入的checked道具。 For example:例如:

render() {
  // here you extract the data from the state
  const age = this.state.age
  const gender = this.state.gender
  ...
  <div className="radio">
    <label><input type="radio" name="gender" onChange={this.setGender.bind(this,'Female')} checked={gender === 'Female'}/> Female</label>
  </div>
  ... // and set checked for every input, using the age for the age radio buttons
 }

Thus, controlling the components like that, when you call reset , all inputs'll have the checked props set to false, and will get unmarked.因此,像这样控制组件,当您调用reset ,所有输入都会将checked道具设置为 false,并且不会被标记。

In ReactJS:在 ReactJS 中:

inputs can be controlled via their value / checked props . inputs可以通过它们的value / checked propscontrolled

These props are typically managed via this.state .这些props通常通过this.state进行管理。

The alternative to controlled components is uncontrolled components . controlled components的替代品是uncontrolled components

See below for a practical example of how to dynamically construct a radio form of controlled components based on an Array of Sections .有关如何基于Sections Array动态构建controlled componentsradio form的实际示例,请参见下文。

 // Sections. const sections = [ { id: 'age', name: 'Age', options: [ '20 - 30', '30 - 40', 'Other' ] }, { id: 'gender', name: 'Gender', options: [ 'Male', 'Female', 'Other' ] } ] // Radio Box class RadioBox extends React.Component { // Constructor. constructor(props) { super(props) this.initialState = sections.reduce((state, section) => ({...state, [section.id]: false}), {}) this.state = this.initialState } // Render. render = () => ( <form onSubmit={this.submit}> {sections.map((section, index) => ( <div key={index}> <span>{section.name}</span> <ul> {section.options.map((option, index) => this.option(section.id, option, index))} </ul> <button type="button" onClick={() => this.setState({[section.id]: false})}>Reset {section.name}</button> </div> ))} <button>Submit</button> <button type="button" onClick={() => this.setState({...this.initialState})}>Clear form</button> </form> ) // Submit. submit = (event) => { event.preventDefault() console.log('Data:', this.state) } // Option. option = (id, option, index) => ( <li key={index}> <label>{option}</label> <input type="radio" checked={this.state[id] == option} onChange={(event) => event.target.checked && this.setState({[id]: option})}/> </li> ) } // Mount. ReactDOM.render(<RadioBox/>, document.querySelector('#root'))
 <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="root"></div>

在这种情况下,您可以使用简单的 jquery 选择器来选择要清除的值,因此您的重置函数将执行以下操作:

$('input[name="age"]').attr('checked', false);

You can add checked property inside your input tag您可以在输入标签中添加checked属性

<input checked={your condition paste here} />

Ex:例如:

<Input type="radio" name="gender" value="male" checked={this.state.gender === "male"} />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM