我在表单上有两个自动完成组件。当第一个自动完成的值更改时,我想更改第二个自动完成的值。请参阅下面的示例代码。当第一个自动完成功能的值更改时,我将“ movie2”设置为状态并将其作为值传递给第二个自动完成功能。但是第二个自动完成功能没有选择该值。任何帮助将不胜枚举。
import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
class Demo extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<>
<Autocomplete
id="combo-box-demo"
value={this.state.movie1}
options={top100Films}
getOptionLabel={option => option.title}
style={{ width: 300 }}
renderInput={params => (
<TextField
{...params}
label="Combo box"
variant="outlined"
fullWidth
/>
)}
onChange={(event, val) => this.setState({ movie1: val, movie2: top100Films[2] })}
/>
<Autocomplete
id="combo-box-demo"
value={this.state.movie2}
options={top100Films}
getOptionLabel={option => option.title}
style={{ width: 300 }}
renderInput={params => (
<TextField
value={this.state.movie2 ? this.state.movie2.title : ""}
{...params}
label="Combo box"
variant="outlined"
fullWidth
/>
)}
/>
</>
);
}
}
export default Demo;
// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
{ title: "The Shawshank Redemption", year: 1994 },
{ title: "The Godfather", year: 1972 },
{ title: "The Godfather: Part II", year: 1974 },
];
答案 0 :(得分:1)
我尝试了您的代码,看来您只需要在构造函数中简单地初始化状态,请尝试以下操作:
constructor(props) {
super(props);
this.state = {
movie1: null,
movie2: null
};
}