reactjs - Material-UI 自动完成组件未将值传播到 TextField 组件
问题描述
我将 Formik 与 Yup 和 Material-UI 一起使用。我有一个包含 Material-UI 自动完成组件的表单我想在提交表单时从自动完成组件中检索用户设置的值。
目前,使用 Autocomplete 组件设置的值似乎没有传播到底层 TextField 组件。当使用自动完成选择一个值并提交表单时,表单上的处理字段上的值为空。
父 (App.js) 组件:
const INITIAL_FORM_STATE = {
treatment: '',
};
const FORM_VALIDATION = Yup.object().shape({
treatment: Yup.string().required('Required'),
});
...
<Formik
initialValues={{ ...INITIAL_FORM_STATE }}
validationSchema={FORM_VALIDATION}
onSubmit={(values) => {
console.log(values);
}}
>
<Form>
<Treatments name='treatment' />
<Buttontype='submit'>Search</Button>
</Form>
</Formik>
治疗组件:
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';
import { InputAdornment } from '@material-ui/core';
import SearchIcon from '@material-ui/icons/Search';
import { useField } from 'formik';
const Treatments = ({ name, ...otherProps }) => {
const [field, meta] = useField(name);
const configTextfield = {
...field,
...otherProps,
fullWidth: true,
variant: 'outlined',
};
if (meta && meta.touched && meta.error) {
configTextfield.error = true;
configTextfield.helperText = meta.error;
}
return (
<Autocomplete
id='treatments'
disableClearable
options={treatments.map((treatment) => treatment.title)}
renderInput={(params) => (
<TextField
{...configTextfield}
{...params}
label='Search for treatments'
margin='normal'
InputProps={{
...params.InputProps,
autoComplete: 'disabled',
type: 'search',
startAdornment: (
<InputAdornment position='start'>
<SearchIcon />
</InputAdornment>
),
}}
/>
)}
/>
);
};
const treatments = [
{ id: 't01', title: 'Foo' },
{ id: 't02', title: 'Bar' },
];
export default Treatments;
我尝试将 a 添加valueRef
到 Treatments 组件并使用onInputChange
Autocomplete 组件上的 prop 设置它,然后将该值分配给inputRef
TextField 组件。但这什么也没做,也没有返回错误。
解决方案
推荐阅读
- security - 使用 jwt 和 2 个服务器作为 secret_key 股东的跨域身份验证
- javascript - 如何处理用户在 Actions on Google 中提供的响应
- react-native - React Native __NSOperationInternal 崩溃报告
- vba - 如何在 Workbook.Close 方法之后运行存储在工作簿模块中的宏?
- java - 隔行扫描 BufferedWriter 和 PrintWriter
- php - onclick 使用 codeigniter 显示来自 dB 的图像
- compiler-construction - 从单个 LLVM IR 指令发出多个 asm 指令的最佳方式
- android - 为什么 MediaPlayer 重新启动后重置位置?
- c# - 使用 CookieAuthenticationProvider 调用 AuthenticationManager.SignIn() 后存储的 ClaimsIdentity 信息在哪里
- linux - Linux cpu hotplug 未按预期工作