我想出了一个解决方案,它不使用 JSON.stringify / parse 作为 select React 元素的值,也不使用选择对象数组的索引作为值。
这个例子是一个简单的选择一个人的性别的下拉菜单——无论是男性还是女性。这些选择中的每一个都是具有 id、text 和 value 属性的实际对象。代码如下:
MySelect 组件
import React, { Component } from 'react';
class MySelect extends Component {
onGenderChange = (event) => {
// Add the second argument -- the data -- and pass it along
// to parent component's onChange function
const data = { options: this.props.options };
this.props.onGenderChange(event, data);
}
render() {
const { options, selectedOption } = this.props;
// Goes through the array of option objects and create an <option> element for each
const selectOptions = options.map(
option => <option key={option.id} value={option.value}>{option.text}</option>
);
// Note that if the selectedOption is not given (i.e. is null),
// we assign a default value being the first option provided
return (
<select
value={(selectedOption && selectedOption.value) || options[0].value}
onChange={this.onGenderChange}
>
{selectOptions}
</select>
);
}
}
使用 MySelect 的应用组件
import _ from 'lodash';
import React, { Component } from 'react';
class App extends Component {
state = {
selected: null
}
onGenderChange = (event, data) => {
// The value of the selected option
console.log(event.target.value);
// The object for the selected option
const selectedOption = _.find(data.options, { value: parseInt(event.target.value, 10) });
console.log(selectedOption);
this.setState({
selected: selectedOption
});
}
render() {
const options = [
{
id: 1,
text: 'male',
value: 123456
},
{
id: 2,
text: 'female',
value: 654321
}
];
return (
<div>
<label>Select a Gender:</label>
<MySelect
options={options}
selectedOption={this.state.selected}
onGenderChange={this.onGenderChange}
/>
</div>
);
}
}
Lodash 用于在 App 组件的 onGenderChange 函数内的选择对象数组中查找选择对象。请注意,传递给MySelect 组件的 onChange 需要两个参数——添加一个额外的数据参数以便能够访问选择对象(“选项”)。这样,您就可以使用所选选项的选择对象来设置状态(或者如果使用 Redux,则调用动作创建者)。