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

React中如何根据RadioButton选择显示/隐藏控件?

React单选按钮联动显示/隐藏输入组件实现方案

以下是修正后的代码,完全满足你点击对应单选按钮时显示/隐藏对应输入组件的需求:

import React, { useState } from 'react'

const App = () => {
  const [selected, setSelected] = useState('')

  const handleRadioChange = (e) => {
    setSelected(e.target.value)
  }

  return (
    <div className="App">
      <form id="custReviewForm">
        {/* Mobile单选按钮 */}
        <input 
          type="radio" 
          id="optMobile" 
          name="options" 
          value="optMobile"
          onChange={handleRadioChange}
          checked={selected === "optMobile"}
        />
        <label htmlFor="optMobile">mobile:</label>
        {/* 选中mobile时显示下拉框 */}
        {selected === "optMobile" && (
          <>
            <br />
            <select name="phoneno" id="phonenumber">
              <option>111-111-1111</option>
              <option>222-222-2222</option>
              <option>333-333-3333</option>
              <option>444-444-4444</option>
            </select>
          </>
        )}
        <br /><br />

        {/* Email单选按钮 */}
        <input 
          type="radio" 
          id="optEmail" 
          name="options" 
          value="optEmail"
          onChange={handleRadioChange}
          checked={selected === "optEmail"}
        />
        <label htmlFor="optEmail">Email:</label>
        {/* 选中Email时显示输入框 */}
        {selected === "optEmail" && (
          <>
            <br />
            <input type="email" id="txtEmail" placeholder="请输入邮箱" />
          </>
        )}
        <br />

        {/* 其他单选按钮 */}
        <input 
          type="radio" 
          id="optCode" 
          name="options" 
          value="optCode"
          onChange={handleRadioChange}
          checked={selected === "optCode"}
        />
        <label htmlFor="optCode">code</label>
        <br />

        <input 
          type="radio" 
          id="optAddress" 
          name="options" 
          value="optAddress"
          onChange={handleRadioChange}
          checked={selected === "optAddress"}
        />
        <label htmlFor="optAddress">address</label>
        <br /><br />

        <input type="submit" value="Submit" />
      </form>
    </div>
  );
}

export default App;

关键修改说明

  • 状态绑定与更新:给每个单选按钮设置唯一value,通过handleRadioChange函数获取选中值并更新selected状态,同时用checked属性同步UI与状态的一致性。
  • 条件渲染控制显示:使用{selected === "目标值" && (...)}的语法,仅当对应单选按钮被选中时,才渲染对应的输入组件(下拉框/邮箱输入框)。
  • 可用性与规范修正:用<label>关联单选按钮,点击文字即可选中选项;将邮箱输入框类型改为email,符合HTML表单规范;修正了重复的id属性,避免DOM冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 20:22:44