Javascript 如何在 React 中使用单选按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29694078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:48:11  来源:igfitidea点击:

How do I use radio buttons in React?

javascriptradio-buttonreactjs

提问by andersem

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?

我正在制作一个表格,我需要一个无线电输入。如何在 onSubmit 函数中获得选中的单选输入,正确的方法是什么?

This is my code, I myRadioInput-variable to contain either Option A or Option B when I submit:

这是我的代码,当我提交时,我的 myRadioInput 变量包含选项 A 或选项 B:

React.createClass({
    handleSubmit: function() {
        e.preventDefault();
        var myTextInput = this.refs.myTextInput.getDOMNode().value.trim();
        var myRadioInput = "How ?";
    },
    render: function() {
        return (
            <form onSubmit={this.handleSubmit}>
                <input type="text" ref="myTextInput" />
                <label>
                    <span>Option A</span>
                    <input type="radio" name="myRadioInput" value="Option A"/>
                </label>
                <label>
                    <span>Option B</span>
                    <input type="radio" name="myRadioInput" value="Option B"/>
                </label>
                <input type="submit" value="Submit this"/>
            </form>
        )
    }
});

采纳答案by Anders Ekdahl

You shouldn't use refs to get access to DOM nodes and inspect their value. Instead you should link the inputs value to a property on the component state.

您不应该使用 refs 来访问 DOM 节点并检查它们的值。相反,您应该将输入值链接到组件状态的属性。

Here are some examples of how to do it: https://facebook.github.io/react/docs/two-way-binding-helpers.html

以下是一些操作示例:https: //facebook.github.io/react/docs/two-way-binding-helpers.html

回答by Jonny Buchanan

If you make sure all your form elements have nameattributes, you can extract data from the form onSubmitusing form.elements:

如果您确保所有表单元素都具有name属性,则可以onSubmit使用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.myRadioInputshould be a RadioNodeListwhich has a .valuecorresponding to the selected value, but when that's not supported you will get a NodeListor HTMLCollectionof nodes which must be iterated over to find the selected value.

在现代浏览器中,form.elements.myRadioInput应该是 a RadioNodeList,它具有.value与所选值对应的a ,但是当不支持时,您将获得 aNodeListHTMLCollectionof 节点,必须对其进行迭代才能找到所选值。



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

我还有一个可重用的 React 组件 -<AutoForm>form.elements为您使用了数据提取的通用实现。我在下面的代码片段中使用了它:

<meta charset="UTF-8">
<script src="http://fb.me/react-0.13.1.js"></script>
<script src="http://fb.me/JSXTransformer-0.13.1.js"></script>
<script src="https://cdn.rawgit.com/insin/react-auto-form/master/dist/react-auto-form.js"></script>
<div id="app"></div>
<script type="text/jsx;harmony=true">void function() { "use strict";
 
var Example = React.createClass({
    getInitialState() {
        return {submittedData: null}
    },

    handleSubmit(e, submittedData) {
        e.preventDefault()
        this.setState({submittedData})
    },

    render() {
        return <div>
            <AutoForm onSubmit={this.handleSubmit}>
                <input type="text" name="myTextInput" />
                <label>
                    <span>Option A</span>
                    <input type="radio" name="myRadioInput" value="Option A"/>
                </label>
                <label>
                    <span>Option B</span>
                    <input type="radio" name="myRadioInput" value="Option B"/>
                </label>
                <input type="submit" value="Submit this"/>
            </AutoForm>
            {this.state.submittedData && <pre>
              {JSON.stringify(this.state.submittedData, null, 2)}
            </pre>}
        </div>
    }
});
 
React.render(<Example/>, document.getElementById('app'))
 
}()</script>

回答by Jayakar Pj

        { items.map(item => 
        <span id="qn" key={item.qno}>{item.qno}</span>
        )}

        { items.map(item => 
        <span id="qd" key={item.qno}>{item.question}<br/>
        <br/>
      <input onClick={this.captureClick} type="radio" value="1" checked={this.state.option === "1"}
            onChange={this.handleChange}/>
        { item.options.map(option => 
        <span id="op" key={option.option1}>
        {option.option1}</span>
        )}<br/>
       <br/> <input onClick={this.captureClick} type="radio" value="2" checked={this.state.option === "2"}
            onChange={this.handleChange} />
        { item.options.map(option => 
        <span id="op" key={option.option2}>
        {option.option2}</span>
        )}<br/><br/>
        <input onClick={this.captureClick} type="radio" value="3" checked={this.state.option === "3"}
            onChange={this.handleChange} />
        { item.options.map(option => 
        <span id="op" key={option.option3}>
        {option.option3}</span>
        )}<br/><br/>

        <input onClick={this.captureClick} type="radio" value="4" checked={this.state.option === "4"}
            onChange={this.handleChange} />

        { item.options.map(option => 
        <span id="op" key={option.option4}>{option.option4}</span>
        )}<br/><br/>
      <button type="submit" className="save" onClick={this.onSave}>SAVE</button>  

        </span>

You can use Radio button's like this also

您也可以像这样使用单选按钮

回答by Mohmmad Ebrahimi Aval

i use this solution for radio button two way binding with active :

我将此解决方案用于单选按钮与 active 的双向绑定:

inside render() method:

在 render() 方法中:

const items = [
    {label: 'one', checked: false},
    {label: 'two', checked: true},
    {label: 'three', checked: true}
];

items.map((item, index) => (
    <div className={`radioItem (item.checked) ? 'active' : ''`}>
        <label>
            {item.label}
            <input type="radio"
                   name="address"
                   value={item.label}
                   onClick={(e)=>{
                       $('.radioItem').filter('.active').removeClass('active');
                       $(e.currentTarget).closest('.radioItem').addClass('active');
                   }}
                   ref={elm => $(elm).prop('checked', item.checked)}
            />
        </label>
    </div>
))