什么是 React TypeScript 的 React.ComponentPropsWithoutRef

use*_*835 17 reactjs react-typescript

对于将 React 与 typescript 一起使用,其React.ComponentPropsWithoutRef用途是什么。该房产有任何文件吗?

ket*_*nde 24

ComponentPropsWithoutRef 类型可用于获取 HTML 元素的所有本机属性作为组件的 props 类型。

您可以简单地创建一个将所有本机按钮属性作为 props 的类型,如下所示:

type ButtonProps = React.ComponentPropsWithoutRef<"button">
const Button = ({ children, onClick, type }: ButtonProps) => {
  return (
    <button onClick={onClick} type={type}>
      {children}
    </button>
  )
}
Run Code Online (Sandbox Code Playgroud)

这里有一个链接更多地讨论了 ComponentPropsWithoutRef 在打字稿中的用法。请参阅“如何输入(扩展)HTML 元素”和“ComponentPropsWithoutRef 与 [Element]HTMLAttributes”部分

  • TLDR: `React.ComponentPropsWithoutRef&lt;"button"&gt;` 比 `React.ButtonHTMLAttributes&lt;HTMLButtonElement&gt;` 短 (6认同)
  • 确实,40 比 45 还小。(◠‿◠) (4认同)