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

React表单Select选项无法提交至后端API的技术求助

React Select组件提交无响应问题排查与修复

问题现象

在React项目中提交表单至后端API时,Input组件提交功能正常,但Select组件的选项无法被识别,提交无任何反应。已为Select绑定value={TypeAInput}与onChange={(e) => setTypeA(e.target.value)},且通过postsType数组映射生成Option的逻辑正常。

原代码

<form onSubmit={ storePost }>

 <div className="field mt-5">
  <label className="label">Type A/label>
                                  
div className="controls">
    <select name="typeA" id="typeA"value={TypeAInput} onChange={(e) => setTypeA(e.target.value)} >
                                
      {
                                       
          postsType.map((category)=>  {
               return(
                     <option className="" value="{category.id}"  >{category.type_a} 
                      </option>
                      )})}
                      </select>  

                            </div>
                                </div>
                               
div className="field mt-5">
  <button className="button is-success is-fullwidth" variant="primary" type="submit">
    Register</button>
                            </div>
                            </form>

错误分析

  • Option的value属性错误使用引号包裹模板字符串:原代码中value="{category.id}"会将字符串{category.id}作为值传递,而非实际的category.id变量值,应改为value={category.id}。
  • 标签语法错误:存在未闭合的<label>标签(原代码写为/label>,缺少起始的<),以及两处<div>标签缺失起始的<符号(div className="controls"和div className="field mt-5")。

修复后的代码

<form onSubmit={storePost}>
  <div className="field mt-5">
    <label className="label">Type A</label>
    <div className="controls">
      <select 
        name="typeA" 
        id="typeA" 
        value={TypeAInput} 
        onChange={(e) => setTypeA(e.target.value)}
      >
        {postsType.map((category) => (
          <option key={category.id} value={category.id}>
            {category.type_a}
          </option>
        ))}
      </select>
    </div>
  </div>

  <div className="field mt-5">
    <button className="button is-success is-fullwidth" variant="primary" type="submit">
      Register
    </button>
  </div>
</form>

注:额外为Option组件添加了key属性,符合React列表渲染规范,可避免不必要的渲染警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:20:39