You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React函数组件中如何获取单选表单(Radio)的值?能否使用useRef Hook实现?

获取React函数组件中单选框选中值的两种方法

嘿,没问题!在React函数组件里获取单选框的值,有两种常用方式——受控组件(React推荐)和useRef Hook,我都给你详细说说:

方法一:受控组件(更符合React数据流)

这是React官方推荐的做法,用useState来管理单选框的选中状态,让状态和UI保持同步,逻辑更清晰易维护。

修改你的代码如下:

import { useState } from 'react';

function PriorityForm() {
  // 初始化选中值,比如默认选中低优先级(value=1),也可以设为null表示默认未选中
  const [selectedPriority, setSelectedPriority] = useState(1);

  const handleButtonClick = () => {
    console.log('选中的优先级值:', selectedPriority);
    // 这里就可以直接用selectedPriority做后续提交、展示等操作啦
  };

  return (
    <div>
      <div className="form-check"> 
        <input 
          type="radio" 
          className="form-check-input" 
          value={3} 
          name="priority"
          checked={selectedPriority === 3}
          onChange={() => setSelectedPriority(3)}
        /> 
        <label className="form-check-label">High Priority</label> 
      </div> 
      <div className="form-check"> 
        <input 
          type="radio" 
          value={2} 
          className="form-check-input" 
          name="priority"
          checked={selectedPriority === 2}
          onChange={() => setSelectedPriority(2)}
        /> 
        <label className="form-check-label">Medium Priority</label> 
      </div> 
      <div className="form-check"> 
        <input 
          type="radio" 
          value={1} 
          className="form-check-input" 
          name="priority"
          checked={selectedPriority === 1}
          onChange={() => setSelectedPriority(1)}
        /> 
        <label className="form-check-label">Low Priority</label> 
      </div>
      <button onClick={handleButtonClick}>获取选中优先级</button>
    </div>
  );
}

简单解释:

  • 用useState声明selectedPriority状态,专门存储当前选中的单选框值
  • 每个单选框的checked属性绑定到状态判断,确保UI和状态完全同步
  • 单选框被点击时,通过onChange事件更新selectedPriority的值
  • 按钮点击时,直接读取selectedPriority就能拿到选中值

方法二:使用useRef Hook

当然可以用useRef实现!这种方式适合不想把单选框状态纳入React状态管理的场景,直接通过DOM元素获取值。

代码示例:

import { useRef } from 'react';

function PriorityForm() {
  // 创建一个ref关联到包裹所有单选框的容器
  const priorityContainerRef = useRef(null);

  const handleButtonClick = () => {
    // 通过ref找到当前选中的单选框
    const selectedRadio = priorityContainerRef.current.querySelector('input[name="priority"]:checked');
    if (selectedRadio) {
      console.log('选中的优先级值:', selectedRadio.value);
      // 拿到值后做后续操作
    } else {
      console.log('还没选中任何优先级哦');
    }
  };

  return (
    <div ref={priorityContainerRef}>
      <div className="form-check"> 
        <input type="radio" className="form-check-input" value={3} name="priority" /> 
        <label className="form-check-label">High Priority</label> 
      </div> 
      <div className="form-check"> 
        <input type="radio" value={2} className="form-check-input" name="priority" /> 
        <label className="form-check-label">Medium Priority</label> 
      </div> 
      <div className="form-check"> 
        <input type="radio" value={1} className="form-check-input" name="priority" /> 
        <label className="form-check-label">Low Priority</label> 
      </div>
      <button onClick={handleButtonClick}>获取选中优先级</button>
    </div>
  );
}

简单解释:

  • 用useRef创建priorityContainerRef,绑定到包裹所有单选框的div上
  • 按钮点击时,通过priorityContainerRef.current拿到DOM容器,再用querySelector定位到选中的单选框
  • 一定要加判断,避免用户没选任何选项时出现报错

小总结

  • 如果你需要根据单选框的选中状态联动其他UI(比如不同优先级显示不同样式),受控组件是更好的选择,状态由React管理,数据流更清晰
  • 如果你只是单纯想在按钮点击时获取一次值,不需要跟踪状态变化,useRef的方式更简单直接

内容的提问来源于stack exchange,提问作者Tamir Polyakov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 06:47:41