如何解决如何清除基于另一个自动完成字段的自动完成材料ui字段?
问题摘要
我在Material UI中有两个“自动完成”字段。第一个(A)包含一个城市的区域列表,第二个(B)包含一个邻域列表,该列表根据A中选择的区域而有所不同。如果A中未选择任何值,则B被禁用。 。除了两个小细节,一切都按预期进行。
- 同时选择A和B上的值,然后从A清除值时,不会清除B的值。
- 当您同时选择A和B的值,然后更改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"},]
}
]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。