【问题标题】:Property '...' does not exist on type 'IntrinsicAttributes & Props'属性 \'...\' 在类型 \'IntrinsicAttributes & Props\' 上不存在
【发布时间】:2022-12-11 19:32:16
【问题描述】:

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

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

我的组件如下所示:

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

  return (
    <input {...htmlProps} />
  );
};

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

“IntrinsicAttributes & Props”类型上不存在属性“已禁用”

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

【问题讨论】:

  • 乍一看,它看起来不错。也许试试extends React.ComponentPropsWithoutRef&lt;'input'&gt;

标签: javascript html reactjs typescript


【解决方案1】:

使用 React.InputHTMLAttributes&lt;HTMLInputElement&gt; 并确保每个附加属性(例如 customProp)都不会到达您的 input。在下面的示例中,因为customProp 是自行销毁的,所以htmlProps 将只包含input 属性。

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

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

【讨论】:

  • 谢谢!该解决方案适用于我在此处发布的简化示例,但不知何故,它会导致我的真实应用程序出现奇怪的样式组件错误。试图弄清楚发生了什么。在这种情况下,@stefanshr 的解决方案对我来说效果更好。
  • 嗨@DariusW!我更新了我的答案,因为 Stefanshr 已被删除,因为我认为它来自 ChatGPT,这违反了 Stack Overflow 准则。请检查我刚刚更新的答案并让我知道。
  • 是的,谢谢!扩展到 React.InputHTMLAttributes<HTMLInputElement> 而不是 React.HTMLAttributes<HTMLInputElement> 解决了我的问题。
猜你喜欢
  • 2021-07-12
  • 2021-02-06
  • 2019-07-31
  • 2021-08-23
  • 2022-12-30
  • 2020-09-03
  • 2021-04-10
  • 1970-01-01
  • 2022-08-18
相关资源
最近更新 更多