问题摘要
我在Material UI中有两个“自动完成”字段。第一个(A)包含一个城市的区域列表,第二个(B)包含一个邻域列表,该列表根据A中选择的区域而有所不同。如果A中未选择任何值,则B被禁用。 。除了两个小细节,一切都按预期进行。
每当A发生更改时,我都尝试将邻域设置为null
,但这不会更改B上显示的值。
要复制的信息和代码
我已经基于Material UI的“自动完成”字段创建了自定义自动完成组件:
const Autosuggest = props => (
<Autocomplete
options={props.options}
getOptionLabel={option => option.title || option}
value={props.value}
style={props.style}
onChange={props.onChange}
disabled={props.disabled}
renderInput={params => (
<TextField
{...params}
label={props.label}
type={props.type}
variant={props.variant}
/>
)}
/>
);
我在另一个包装器组件中包括了它的两个实例:
const Wrapper = props => {
// Some variables
const {selectedDistrict} = props
let district = selectedDistrict ? selectedDistrict.title : "";
let neighbourhoods = selectedDistrict ? selectedDistrict.neighbourhoods : [];
return (
<Div>
<Autosuggest
options={props.autosuggestData}
value={district}
onChange={props.setDistrict}
variant="outlined"
label="Distrito"
style={AutosuggestStyle}
/>
<Autosuggest
key={props.selectedNeighbourhood}
options={neighbourhoods}
value={props.selectedNeighbourhood}
disabled={district ? false : true}
onChange={props.setNeighbourhood}
variant="outlined"
label="Barrio"
style={AutosuggestStyle}
/>
</Div>
);
};
然后我在主要的App组件中使用包装器:
export default class App extends Component {
constructor(props){
super(props)
this.state = {
district: "",
neighbourhood: ""
}
this.setDistrict = this.setDistrict.bind(this);
this.setNeighbourhood = this.setNeighbourhood.bind(this);
}
// Methods
setDistrict = (event, value) => {
this.setState({
district: value,
neighbourhood: null
}, () => console.log("New district set: ", this.state.district))
}
setNeighbourhood = (event, value) => {
let hood = value ? value : null;
this.setState({
neighbourhood: hood
}, () => console.log("New neighbourhood set: ", this.state.neighbourhood))
}
render() {
return (
<Wrapper
autosuggestData={districts}
setDistrict={this.setDistrict}
setNeighbourhood={this.setNeighbourhood}
selectedDistrict={this.state.district}
selectedNeighbourhood={this.selectedNeighbourhood}
/>
)
}
}
这是我使用的地区和社区的示例:
let districts = [
{
title: "Ciutat Vella",
neighbourhoods : [
{title : "La Barceloneta"},
{title : "El Gòtic"},
{title : "El Raval"},
{title : "Sant Pere"},
{title : "Santa Caterina i la Ribera"}
]
},
{
title: "Eixample",
neighbourhoods : [
{title : "L'Antiga Esquerra de l'Eixample"},
{title : "La Nova Esquerra de l'Eixample"},
{title : "Dreta de l'Eixample"},
{title : "Fort Pienc"},
{title : "Sagrada Família"},
{title : "Sant Antoni"},
]
}
]