如何在React中使用单选按钮? [英] How do I use radio buttons in React?

查看:688
本文介绍了如何在React中使用单选按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作表格,我需要收音机输入。如何在onSubmit函数中获取已检查的无线电输入,这是正确的方法?

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?

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

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

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>
        )
    }
});


推荐答案

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

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.

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

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

这篇关于如何在React中使用单选按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆