我正在React中工作,我有一个小的表格可以从另一个.js文件中提取数据。选择框的几个数据取决于另一个的数据数组。以下是基于传统性别的传统名称示例的代码。我添加了一个randomize函数,该函数将根据console.log中的性别生成正确的名称,但实际上不会更改Name选择框的值。
随机选择时,性别选择框会在视觉上完美变化,但我无法更改名称选择框-我猜是因为它需要以某种方式引用数组中随机选择的性别?预先感谢!
form.js
onGenderChange = (e) => {
const gender = e.target.value;
this.setState(() => ({ gender }));
};
onNameChange = (e) => {
const name = e.target.value;
this.setState(() => ({ name }));
};
onRandomize = (e) => {
const randGender = genders[Math.floor(Math.random() * genders.length)].value;
this.setState(() => ({ gender: randGender }));
const randName = names[randGender][Math.floor(Math.random() * names[randGender].length)].value;
this.setState(() => ({ name: randName }));
}
<label htmlFor="selectGender">Gender</label>
<select
className="select"
name="selectGender"
onChange={this.onGenderChange}
value={this.state.gender}
>
<option value="defaultGender" defaultValue>Select a Gender</option>
{
genders != undefined &&
genders.map( gender =>
<option key={gender.value} value={gender.value}>{gender.name}</option>)
}
</select>
<label htmlFor="selectName">Name</label>
<select
className="select"
name="selectName"
onChange={this.onNameChange}
value={this.state.name}
>
<option value="defaultName" defaultValue>Select a Name</option>
{
names != undefined &&
names.map( name =>
<option key={name.value} value={name.value}>{name.name}</option>)
}
</select>
formData.js
const genders = [
{ value: "Female", name: "Female" },
{ value: "Male", name: "Male" }
];
const names = {
'Female': [
{ value: "Jane", name: "Jane" },
{ value: "Suzanne", name: "Suzanne" }
],
'Male': [
{ value: "John", name: "John" },
{ value: "Steve", name: "Steve" }
]
};