ReactJS Select组件如何显示双值但仅传递ID渲染表格?
解决Select组件同时显示ID和名称但仅传递ID的问题
嘿,这个问题我之前也碰到过,其实核心就是你没给<option>设置value属性!目前你的代码里,<option>只显示了planet.id,但如果想同时展示ID和名称,直接把内容改成{planet.id} - {planet.name}的话,event.target.value会默认取这个显示的文本字符串,自然就传递了两个值,导致表格渲染出错。
正确的做法
给<option>明确设置value属性为planet.id,这样不管你显示什么内容,表单 onChange 时拿到的都是纯ID:
class Planet extends React.Component { constructor(props) { super(props); this.state = {value: 1}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event){ this.setState({value: event.target.value}); // 这里拿到的event.target.value就是planet.id的字符串形式,直接用来渲染表格就没问题了 } render () { let planets = this.props.state.planets; let optionItems = planets.map((planet) => // 给option设置value为planet.id,显示内容同时放ID和名称 <option key={planet.id} value={planet.id}>{planet.id} - {planet.name}</option> ); // 后续的render逻辑... } }
补充说明
key={planet.id}是React用来优化列表渲染的标识,和表单传递的值没有关系,它只是让React能高效识别列表项的变化,不会影响event.target.value的取值。- 如果你的
planet.id是数字类型,event.target.value会自动转成字符串,要是后续需要数字格式,可以用parseInt(event.target.value, 10)转一下。
这样修改后,你既能在Select选项里同时展示ID和名称,又能在选择时只获取到ID,用来渲染表格就完全没问题啦!
内容的提问来源于stack exchange,提问作者zemmsoares
相关产品推荐
相关产品推荐

