reactjs 将组件属性正确扩展为默认html按钮属性

9lowa7mx  于 2023-01-17  发布在  React
关注(0)|答案(2)|浏览(134)

我正在开发一个按钮组件,它有variant属性来决定它的颜色。

interface Props extends React.HTMLProps<HTMLButtonElement> {
  variant: 'yellow' | 'green';
}

function Button({ variant, ...props }: Props) {
  console.log(variant);

  return (
    <button
      type="button"
      {...props}
    />
  );
}

我的type下出现打字错误,内容如下:
(JSX属性)按钮HTMLA属性。类型?:"按钮"|"提交"|"复位"|未定义类型"string"不能分配给类型"button"|"提交"|"复位"|未定义'. ts(2322)索引. d. ts(1872,9):所需类型来自此处在类型"DetailedHTMLProps,HTMLButtonElement〉"上声明的属性"type"
所以我不确定我是否正确地延伸到按钮 prop ?也许还有另一种方法?

tjrkku2a

tjrkku2a1#

应该使用ButtonHTMLAttributes而不是HTMLProps,如下所示:

interface Props extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  variant: 'yellow' | 'green';
}

function Button({ variant, ...props }: Props) {
  console.log(variant);

  return (
    <button
      type="button"
      {...props}
    />
  );
}
qv7cva1a

qv7cva1a2#

2023年更新

如果您想创建按钮而不需要任何额外内容,可以扩展React.ComponentPropsWithoutRef<"button">,对于试图创建可重用组件的人,需要将底层元素扩展为forwardRef,然后可以使用ComponentPropsWithRef

interface Props extends React.ComponentPropsWithoutRef<"button"> {
  variant: 'yellow' | 'green';
}

为什么不使用React.HTMLAttributes<HTMLButtonElement>呢?
这是当您使用以下命令时发生的情况:

export interface ButtonProps extends React.HTMLAttributes<HTMLButtonElement> {
  /* etc */
}

function App() {
  // Property 'type' does not exist on type 'IntrinsicAttributes & ButtonProps'
  return <Button type="submit"> text </Button>;
}

旧答案

Codesandbox Live Preview
你可能要找的是React.HTMLAttributes<HTMLButtonElement>

import * as React from "react";
import { render } from "react-dom";

import "./styles.css";

interface Props extends React.HTMLAttributes<HTMLButtonElement> {
  variant: 'yellow' | 'green';
}

function Button({ variant, ...props }: Props) {

  return (
    <button
      type="button"
      {...props}
    />
  );
}

const rootElement = document.getElementById("root");
render(<Button variant='green' />, rootElement);

为了更精确,我们可以使用React.ButtonHTMLAttributes<HTMLButtonElement>

import * as React from "react";
import { render } from "react-dom";

import "./styles.css";

interface Props extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  variant: 'yellow' | 'green';
}

function Button({ variant, ...props }: Props) {

  return (
    <button
      type="button"
      {...props}
    />
  );
}

const rootElement = document.getElementById("root");
render(<Button variant="green" />, rootElement);

相关问题