React中如何通过radio单选框传递表格整行对象数据
问题根因
HTML原生input的value属性仅支持字符串类型值:
- 直接传入JS对象时,DOM会自动执行对象到字符串的类型转换,最终输出
[object Object],丢失所有原始字段 - 写
value={creative.ad_type, creative.ad_title}时用到了JS逗号运算符,该运算符只会返回最后一个表达式的执行结果,因此只能拿到最后一个字段的值 - 额外注意:你原代码里写的
class="checkbox1"不符合JSX语法规范,React中元素类名必须用className属性;循环内给所有radio写相同的id="chk"也违反HTML id全局唯一的规则,建议删掉。
实现方案
方案1:回调直接传当前行对象(推荐,写法最简单)
不要把对象绑定到value属性上,在绑定点击事件时直接把当前遍历到的行对象作为参数传入处理函数即可。
修改后的表格渲染代码:
<table className="table table-bordered table-stripped"> <thead> <th>AD Type</th> <th>AD Title</th> <th>Image/Video URL</th> <th>Video Thumbnail</th> <th>Landing URL</th> <th>Placement</th> <th>Country</th> <th>DSP</th> <th>Select</th> </thead> <tbody> { creative.map( // 这里把遍历参数改个名,避免和外层数组名creative重名造成歧义 creativeItem => <tr key={creativeItem.id}> <td>{creativeItem.ad_type}</td> <td>{creativeItem.ad_title}</td> <td>{creativeItem.image_url}</td> <td>{creativeItem.video_thumbnail}</td> <td>{creativeItem.landing_url}</td> <td>{creativeItem.placement}</td> <td>{creativeItem.country}</td> <td>{creativeItem.dsp}</td> <td> <input type="radio" className="checkbox1" name="check[]" onClick={(e) => func1(e, creativeItem)} /> </td> </tr> ) } </tbody> </table>
对应的处理函数修改为接收两个参数:
const func1 = (e, currentRowData) => { // currentRowData就是当前选中行的完整creative对象,所有字段都可以直接访问 console.log(currentRowData); }
方案2:通过唯一ID匹配原始数据
如果需要保留value属性传值的逻辑,可以把每行数据的唯一标识(比如creative.id)存在value中,触发事件时拿这个ID从原始数组中匹配到完整行数据。
input部分代码:
<input type="radio" className="checkbox1" name="check[]" value={creativeItem.id} onClick={func1} />
对应的处理函数:
const func1 = (e) => { const selectedId = e.target.value; // 从原始creative数组中匹配id对应的完整对象 const currentRowData = creative.find(item => item.id == selectedId); console.log(currentRowData); }
小提示:两种方案都能实现需求,方案1不需要额外做数组匹配,性能更好代码也更简洁,优先选这个就行。
内容的提问来源于stack exchange,提问作者Shlok Sharma
相关产品推荐
相关产品推荐

