How do I use radio buttons in React?

前端 未结 4 1869
别那么骄傲
别那么骄傲 2021-02-13 22:36

I\'m making a form, and I was in need of a radio input. How do I get the checked radio input in a onSubmit-function, what is the correct way?

This is my code, I myRadioI

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-13 22:49

    If you make sure all your form elements have name attributes, you can extract data from the form onSubmit using form.elements:

    handleSubmit: function(e) {
      e.preventDefault()
      var form = e.target
      var myTextInput = form.elements.myTextInput.value
      var myRadioInput = form.elements.myRadioInput.value
      // ...
    }
    

    In modern browsers, form.elements.myRadioInput should be a RadioNodeList which has a .value corresponding to the selected value, but when that's not supported you will get a NodeList or HTMLCollection of nodes which must be iterated over to find the selected value.


    I also have a reusable React component - - which uses a generic implementation of data extraction from form.elements for you. I've used it in the snippet below:

    
    
    
    
    

提交回复
热议问题