ReactJS Material UI 如何防止Autocomplete改变值
ReactJS Material UI how to prevent Autocomplete to change the value
我有一个自动完成组件,我需要阻止它选择某种值。
const options = ["Option 1", "Option 2", "Option 3"];
const [value, setValue] = React.useState(options[0]);
const [inputValue, setInputValue] = React.useState("");
const change = (event, newValue) => {
event.preventDefault();
event.stopPropagation();
if (newValue !== "Option 3") {
setValue(newValue);
}
};
console.log(value);
return (
<div>
<Autocomplete
value={value}
onChange={change}
inputValue={inputValue}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
id="controllable-states-demo"
disableClearable
options={options}
style={{ width: 300 }}
renderInput={(params) => (
<TextField {...params} label="Controllable" variant="outlined" />
)}
/>
</div>
);
目前条件不会更改状态,但会更改组件上的值。我怎样才能防止这种情况发生?
Here 是沙箱。
您又在此处设置值,请勿在此事件上更新
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
设置输入值={值}
更新于此,
https://codesandbox.io/s/material-demo-forked-jmr6e?file=/demo.js
我有一个自动完成组件,我需要阻止它选择某种值。
const options = ["Option 1", "Option 2", "Option 3"];
const [value, setValue] = React.useState(options[0]);
const [inputValue, setInputValue] = React.useState("");
const change = (event, newValue) => {
event.preventDefault();
event.stopPropagation();
if (newValue !== "Option 3") {
setValue(newValue);
}
};
console.log(value);
return (
<div>
<Autocomplete
value={value}
onChange={change}
inputValue={inputValue}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
id="controllable-states-demo"
disableClearable
options={options}
style={{ width: 300 }}
renderInput={(params) => (
<TextField {...params} label="Controllable" variant="outlined" />
)}
/>
</div>
);
目前条件不会更改状态,但会更改组件上的值。我怎样才能防止这种情况发生?
Here 是沙箱。
您又在此处设置值,请勿在此事件上更新
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
设置输入值={值}
更新于此, https://codesandbox.io/s/material-demo-forked-jmr6e?file=/demo.js