[英]React select elements value is setting state to the previous selected options value?
On my select element in React, the first couple of selects aren't changing the value, but then they start changing the value to the previous selected option, like if I select the option FRITOS, the value is undefined, then when I select the選項 COFFEE,值是 FRITOS,然后當我再次 select FRITOS 時,值變為 COFFEE。 真的很困惑這是怎么回事哈哈。
我的 function 正在設置 state
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 元件
<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>
[以前的答案很愚蠢,讓我們編輯!]
您可以通過將 select 放入組件中來觸發重新渲染:
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 並使用功能組件和鈎子,這將不再是問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.