HTMLInputElement在元素类型之间切换时抛出类型错误



我正在尝试编写这个React GraphQL TypeScript教程

目标:基本上HTML元素类型应该设置为元素'Textarea',如果默认变量:' Textarea' = true,设置为元素'Input',如果变量:' Textarea' = false。

目前我在分钟6:05:28,我被困在以下错误,没有出现在视频中,我不知道为什么。我意识到这并没有真正影响任何事情(事情仍然有效),但它显示了一个红色下划线错误,这是相当烦人的:

Type 'ComponentWithAs<"textarea", TextareaProps>' is not assignable to type 'ComponentWithAs<"input", InputProps>'.
Types of parameters 'props' and 'props' are incompatible.
Type 'MergeWithAs<DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>, any, InputProps, any>' is not assignable to type 'MergeWithAs<DetailedHTMLProps<TextareaHTMLAttributes<HTMLTextAreaElement>, HTMLTextAreaElement>, any, TextareaProps, any>'.
Type 'MergeWithAs<DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>, any, InputProps, any>' is not assignable to type 'OmitCommonProps<DetailedHTMLProps<TextareaHTMLAttributes<HTMLTextAreaElement>, HTMLTextAreaElement>, keyof TextareaProps>'.
Types of property 'ref' are incompatible.
Type 'LegacyRef<HTMLInputElement> | undefined' is not assignable to type 'LegacyRef<HTMLTextAreaElement> | undefined'.
Type '(instance: HTMLInputElement | null) => void' is not assignable to type 'LegacyRef<HTMLTextAreaElement> | undefined'.
Type '(instance: HTMLInputElement | null) => void' is not assignable to type '(instance: HTMLTextAreaElement | null) => void'.
Types of parameters 'instance' and 'instance' are incompatible.
Type 'HTMLTextAreaElement | null' is not assignable to type 'HTMLInputElement | null'.
Type 'HTMLTextAreaElement' is missing the following properties from type 'HTMLInputElement': accept, align, alt, capture, and 26 more.

给出的行错误是:InputOrTextarea被用红色突出显示,上面的错误

InputOrTextarea = Textarea;

完整代码是:

type InputFieldProps = InputHTMLAttributes<HTMLInputElement> & {
label: string;
name: string;
textarea?: boolean;
};
export const InputField: React.FC<InputFieldProps> = ({
label, 
textarea,
size: _,
...props
}) => {
let InputOrTextarea = Input;
if (textarea) {
InputOrTextarea = Textarea;
}
const [field, {error, }] = useField(props);
return (
<FormControl isInvalid = {!!error}>
<FormLabel htmlFor={field.name}>{label}</FormLabel>
<InputOrTextarea {...field} {...props} id = {field.name} placeholder={props.placeholder}/>
{error ? <FormErrorMessage>{error}</FormErrorMessage> : null}
</FormControl>
);
}

你或其他人:

我也有同样的问题,我在看同样的视频。你需要将import从'@chakra-ui/react'更改为'@chakra-ui/core'。

我正在使用'@chakra-ui/core',它给了我一个错误。当我安装"yarn add @chakra-ui/core @emotion/core @emotion/styled emotion- theme"并使用core导入时,错误就消失了。

您可以尝试强制InputOrTextarea上的类型允许将输入或文本区域分配给它。例如:

let InputOrTextarea: HTMLInputElement | HTMLTextAreaElement | null = Input;
if (textarea) {
InputOrTextarea = Textarea;
}

相关内容

最新更新