gpt4 book ai didi

reactjs - typescript react : How to override default html input element attribute prop types

转载 作者:行者123 更新时间:2023-12-05 09:37:21 29 4
gpt4 key购买 nike

我正在尝试创建自定义“输入”组件并扩展默认的 html 输入属性(props)。

但是,我也尝试在我自己的接口(interface)定义中使用 Typescript 的 Omit 覆盖默认的“大小”属性,但似乎无法让它工作。

(我也尝试过 Typescript 的 Pick/Exclude 和自定义的 Override 类型,但得到同样的错误...)

我已经尝试过的类似主题:

import React from 'react';

type A = React.HTMLAttributes<HTMLInputElement>;

interface InputProps extends Omit<A, 'size'> {
size?: 'sm' | 'md' | 'lg';
}

const Input = (props: InputProps) => {
return <input {...props} />;
};

TS 错误

(property) JSX.IntrinsicElements.input: React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>
Type '{ size?: "sm" | "md" | "lg"; defaultChecked?: boolean; defaultValue?: string | number | readonly string[]; suppressContentEditableWarning?: boolean; ... 250 more ...; onTransitionEndCapture?: (event: TransitionEvent<...>) => void; }' is not assignable to type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'.
Type '{ size?: "sm" | "md" | "lg"; defaultChecked?: boolean; defaultValue?: string | number | readonly string[]; suppressContentEditableWarning?: boolean; ... 250 more ...; onTransitionEndCapture?: (event: TransitionEvent<...>) => void; }' is not assignable to type 'InputHTMLAttributes<HTMLInputElement>'.
Types of property 'size' are incompatible.
Type 'string' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.ts(2322)

最佳答案

interface InputProps.... 替换为

type InputProps = {
size?: 'sm' | 'md' | 'lg';
} & Omit<A, 'size'>;

根据 OP 的评论,

const Input = ({ size, ...props }: InputProps) => {
// if(size) do something...
return <input {...props} />;
};

关于reactjs - typescript react : How to override default html input element attribute prop types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64274764/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com