[英]React MUI Autocomplete - managing onChange event from the parent component
我的目标是通过属于子组件的onChange事件从父组件触发自定义 function。 在我的例子中,子组件是 React MUI 自动完成组件。
考虑文档中有关可控状态的示例:
import * as React from 'react';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';
const options = ['Option 1', 'Option 2'];
export default function ControllableStates() {
const [value, setValue] = React.useState(options[0]);
const [inputValue, setInputValue] = React.useState('');
return (
<div>
<div>{`value: ${value !== null ? `'${value}'` : 'null'}`}</div>
<div>{`inputValue: '${inputValue}'`}</div>
<br />
<Autocomplete
value={value}
onChange={(event, newValue) => {
setValue(newValue);
}}
inputValue={inputValue}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
id="controllable-states-demo"
options={options}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Controllable" />}
/>
</div>
);
}
如您所见,已定义 onChange 事件以更新新值。 行。
通常,我从父组件操作这个事件的方式很简单:
import * as React from 'react';
import ReactDOM from 'react-dom/client';
import { StyledEngineProvider } from '@mui/material/styles';
import Demo from './demo';
function handleChange(event)
{
console.log("Hello!")
}
ReactDOM.createRoot(document.querySelector("#root")).render(
<StyledEngineProvider injectFirst>
<Demo onChange={handleChange} />
</StyledEngineProvider>
);
但在这种情况下它不起作用,可能是因为 onChange 已被自动完成组件“占用”。
有解决方法吗?
对于那些将面临同样问题的人:
不知道有没有办法直接从父组件使用onChange,不过我换了个方法解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.