我以前从未在
helperText
组件上遇到过 TextField
的问题,但我刚刚升级到 React-scripts 5,这基本上破坏了很多东西,因为我的打字稿很弱。不管怎样,下面有一些关于实际发生的事情的更多信息。
错误:
TS2322: Type 'string | false | string[] | FormikErrors<any> | FormikErrors<any>[] | undefined' is not assignable to type 'ReactNode'.
313 | touched.controlType && errors.controlType,
314 | )}
> 315 | helperText={touched.controlType && errors.controlType}
| ^^^^^^^^^^
316 | label="Control type"
317 | name="controlType"
318 | variant="filled"
代码:
<Autocomplete
disableClearable={false}
disableCloseOnSelect={false}
onBlur={handleBlur}
onChange={(_, value) => setFieldValue('controlType', value)}
options={CONTROL_TYPES || []}
filterSelectedOptions
renderInput={(params) => (
<TextField
error={Boolean(
touched.controlType && errors.controlType,
)}
helperText={touched.controlType && errors.controlType}
label="Control type"
name="controlType"
variant="filled"
{...params}
/>
)}
value={values.controlType}
/>
我遇到了同样的问题,事实证明在这种情况下最好手动检查错误内容的类型。该解决方案实际上已记录在here。
以下为我解决了这个问题:
helperText={(touched.controlType && errors.controlType && typeof errors.controlType === 'string') && errors.controlType}"
{...params}
您也可以摆脱第一个“errors.controlType”,但我相信首先检查空值更安全。
问题在于您的类型注释。理想情况下,您应该正确设置它们。我怀疑 controlType 的类型要么设置为
any
要么设置不正确。我遇到了类似的情况any
(见下面的例子)
const controlType: any = your data
但是如果你设置为
const controlType: IControlType = your data
错误可能会消失。
<Formik
initialValues={controlType}
假设您只有一个组件。
虽然上面建议的解决方案有效,但我觉得这不是正确的修复方法。
helperText={(touched.controlType && errors.controlType && typeof errors.controlType === 'string') && errors.controlType}"
{...params}