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

ReactJS中如何获取单选框选项值?解决onChange事件‘Expected onChange listener to be a function, instead got a value of object type.’报错问题

问题解决:单选框onChange错误&值获取方法

嘿,我一眼就揪出问题所在啦!你看到的错误提示"Expected onChange listener to be a function, instead got a value of object type.",是因为你把状态对象sectionAData直接传给了单选框的onChange属性——但onChange明确要求接收的是一个函数,不是对象哦!

第一步:修正onChange绑定

把所有单选框的onChange={sectionAData}改成onChange={handleSectionA},也就是绑定你写好的处理函数。修正后的表单代码如下:

<tr>
  <td style={{ width: "2rem", textAlign: "center" }}>1</td>
  <td style={{padding:"5px"}}>Please rate this product A.</td>
  <td style={{textAlign: "center" }}><input type="radio" name="AQ1" onChange={handleSectionA} value="5"/></td>
  <td style={{textAlign: "center" }}><input type="radio" name="AQ1" onChange={handleSectionA} value="4"/></td>
  <td style={{textAlign: "center" }}><input type="radio" name="AQ1" onChange={handleSectionA} value="3"/></td>
  <td style={{textAlign: "center" }}><input type="radio" name="AQ1" onChange={handleSectionA} value="2"/></td>
  <td style={{textAlign: "center" }}><input type="radio" name="AQ1" onChange={handleSectionA} value="1"/></td>
</tr>
<tr>
  <td style={{ width: "2rem", textAlign: "center" }}>2</td>
  <td>Please rate this product B.</td>
  <td style={{textAlign: "center" }}><input type="radio" name="AQ2" onChange={handleSectionA} value="5"/></td>
  <td style={{textAlign: "center" }}><input type="radio" name="AQ2" onChange={handleSectionA} value="4"/></td>
  <td style={{textAlign: "center" }}><input type="radio" name="AQ2" onChange={handleSectionA} value="3"/></td>
  <td style={{textAlign: "center" }}><input type="radio" name="AQ2" onChange={handleSectionA} value="2"/></td>
  <td style={{textAlign: "center" }}><input type="radio" name="AQ2" onChange={handleSectionA} value="1"/></td>
</tr>
<tr>
  <td style={{ width: "2rem", textAlign: "center" }}>3</td>
  <td>Please rate this product C.</td>
  <td style={{textAlign: "center" }}><input type="radio" name="AQ3" onChange={handleSectionA} value="5"/></td>
  <td style={{textAlign: "center" }}><input type="radio" name="AQ3" onChange={handleSectionA} value="4"/></td>
  <td style={{textAlign: "center" }}><input type="radio" name="AQ3" onChange={handleSectionA} value="3"/></td>
  <td style={{textAlign: "center" }}><input type="radio" name="AQ3" onChange={handleSectionA} value="2"/></td>
  <td style={{textAlign: "center" }}><input type="radio" name="AQ3" onChange={handleSectionA} value="1"/></td>
</tr>

第二步:获取单选框选中的值

当用户点击单选框后,你的handleSectionA函数会把选中的值更新到sectionAData状态里。之后你可以直接通过状态对象来获取对应选项的值:

  • 获取产品A的评分:sectionAData.AQ1
  • 获取产品B的评分:sectionAData.AQ2
  • 获取产品C的评分:sectionAData.AQ3

举个例子,如果你想在某个地方展示选中的评分,可以这么写:

<p>产品A的评分:{sectionAData.AQ1 || '未选择'}</p>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 13:52:35