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

How do I use radio buttons in React?(如何在 React 中使用单选按钮?)
本文介绍了如何在 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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)