使用 react-hook-form (Material-UI) 更改自动完成值
Changing Autocomplete value using react-hook-form (Material-UI)
我有两个自动完成字段,我的目标是通过第一个字段的值更改第二个字段的值。
我遇到的问题是,当我尝试将新值发送到“setValue”函数时,状态表单没有任何变化,但自动完成字段显示旧值。
在这个沙盒中:
https://codesandbox.io/s/dazzling-carson-84dxp?file=/src/Form/Components/UserCountry.js
你可以看到我的实现。
如果您在更改 user_name
字段时查看控制台,您可以在控制台中看到 materialUI 警告:
Material-UI: 某个组件正在将Autocomplete的不受控值状态更改为受控。
原因是你的user_country
的默认值是undefined
,material认为这个字段是不受控制的字段,这意味着material会控制user_country
个值。要解决这个问题,您有两个解决方案:
1- 通过 defaultValues
选项定义表单,如下所示:
const methods = useForm({
defaultValues: {
user_name: null,
user_country: null
}
});
2- 当 null
没有任何值时将其作为值发送给 AutoComplete
,如下所示:
<Controller
control={control}
name={`user_country`}
render={({ field: { onChange, value } }) => (
<Autocomplete
id="country-select-demo"
options={countries}
onChange={(event, item) => {
onChange(item);
}}
value={value || null}
...
/>
)}
/>
Here 您可以看到您的表单在您更改 user_name
字段时更新 user_country
。
我有两个自动完成字段,我的目标是通过第一个字段的值更改第二个字段的值。
我遇到的问题是,当我尝试将新值发送到“setValue”函数时,状态表单没有任何变化,但自动完成字段显示旧值。 在这个沙盒中: https://codesandbox.io/s/dazzling-carson-84dxp?file=/src/Form/Components/UserCountry.js
你可以看到我的实现。
如果您在更改 user_name
字段时查看控制台,您可以在控制台中看到 materialUI 警告:
Material-UI: 某个组件正在将Autocomplete的不受控值状态更改为受控。
原因是你的user_country
的默认值是undefined
,material认为这个字段是不受控制的字段,这意味着material会控制user_country
个值。要解决这个问题,您有两个解决方案:
1- 通过 defaultValues
选项定义表单,如下所示:
const methods = useForm({
defaultValues: {
user_name: null,
user_country: null
}
});
2- 当 null
没有任何值时将其作为值发送给 AutoComplete
,如下所示:
<Controller
control={control}
name={`user_country`}
render={({ field: { onChange, value } }) => (
<Autocomplete
id="country-select-demo"
options={countries}
onChange={(event, item) => {
onChange(item);
}}
value={value || null}
...
/>
)}
/>
Here 您可以看到您的表单在您更改 user_name
字段时更新 user_country
。