类型“IntrinsicAttributes & Props”上不存在属性“...”

Dar*_*usW 7 html javascript typescript reactjs

我的应用程序中有一个<InputField>组件,其属性的类型定义如下:

interface InputFieldProps extends React.HTMLAttributes<HTMLInputElement> {
  customProp: string;
}
Run Code Online (Sandbox Code Playgroud)

我的组件如下所示:

const InputField: React.FC<InputFieldProps> = ({ customProp, ...htmlProps }) => {

  return (
    <input {...htmlProps} />
  );
};
Run Code Online (Sandbox Code Playgroud)

我希望现在可以将 propdisabled或传递required给该组件,因为这些属性是 HTMLInputElement 类型定义的一部分。但是,我收到错误:

类型“IntrinsicAttributes & Props”上不存在属性“disabled”

我尝试通过残疾人disabled={true}以及但disabled没有成功。不过,我可以placeholder作为道具通过。因此 HTMLInputElement 类型定义中的某些属性似乎有效,而其他属性则无效。

You*_*mar 5

使用React.InputHTMLAttributes<HTMLInputElement>就对了。只需确保任何其他属性(例如 )customProp不会到达您的input。在下面的示例中,由于customProp会自行破坏,inputProps因此仅包含input属性。

interface InputFieldProps extends React.InputHTMLAttributes<HTMLInputElement> {
  customProp: string;
}

const InputField: React.FC<InputFieldProps> = ({
  customProp,
  ...inputProps
}) => {
  return <input {...inputProps} />;
};
Run Code Online (Sandbox Code Playgroud)

编辑 愤怒-快速-upe615