在React的select元素上,前两个选择未更改值,但随后它们开始将值更改为上一个选定的选项,例如如果我选择选项FRITOS,则该值未定义,然后我选择选项COFFEE,其值为FRITOS,然后再次选择FRITOS时,该值变为COFFEE。真的很困惑哈哈。
我正在设置状态的功能
changeGroup = (event) => {
this.setState({ [event.target.name]: event.target.value });
console.log(this.state.groupSelected);
const bugQuery = {
GroupID: this.state.groupSelected,
};
console.log(bugQuery);
console.log(this.props.bugs);
if (this.state.groupSelected !== undefined) {
this.props.getBugs(bugQuery);
}
};
我的选择元素
<select
style={{ border: "1px solid white", fontSize: "2.7vh" }}
name="groupSelected"
value={this.state.groupSelected}
onChange={this.changeGroup}
>
<option value="FRITOS">FRITOS</option>
<option value="5AFSA">5AFSA</option>
<option selected>Groups</option>
</select>
答案 0 :(得分:-1)
[上一个答案很愚蠢,让我们编辑!]
您可以通过将选择放入组件中来触发重新渲染:
import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import "./style.css";
class App extends Component {
constructor() {
super();
this.options = ["FRITOS", "SAFSA"];
this.state = {
name: "React",
groupSelected:''
};
}
changeGroup = event => {
this.setState({[event.target.name]: event.target.value }, () => console.log(this.state.groupSelected));
};
render() {
return (
<div>
<Hello name={this.state.name} />
<MySelect
options={this.options}
selectedOption={this.state.groupSelected}
onSelectChange={this.changeGroup} />
<div>groupSelected = {this.state.groupSelected}</div>
</div>
);
}
}
class MySelect extends Component {
constructor(props) {
super(props);
this.options = ["FRITOS", "SAFSA"];
}
buildSelectOptions = () => {
return this.props.options.map(option => (
<option key={option} value={option}>
{option}
</option>
));
};
render() {
return (
<>
<select
style={{ border: "1px solid white", fontSize: "2.7vh" }}
name="groupSelected"
value={this.props.groupSelected}
onChange={this.props.onSelectChange}
>
{this.buildSelectOptions()}
<option selected>Groups</option>
</select>
</>
);
}
}
render(<App />, document.getElementById("root"));
自从您使用this.setState以来,我一直使用旧方法,但是如果可以的话,请升级到最新版本的react并使用功能组件和挂钩,这将不再是问题。