反应-如何将DOMAttribute添加到自定义组件?

时间:2019-12-01 19:58:09

标签: reactjs typescript

我在打字稿中有一个自定义的React组件:

const MyButton: React.FC = ({children, ...props}) => {
  return (<button {...props}>{children}</button>)
}

当我尝试使用此组件时,添加一个DOMAttribute(例如onClick):

<MyButton onClick={() => console.log("clicked")}></MyButton>

我收到此错误:

Type '{ onClick: () => void; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
  Property 'onClick' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.ts(2322)

如何修改MyButton使其接受DOMAttributes?

1 个答案:

答案 0 :(得分:0)

您必须使用HTMLAttributes<HTMLButtonElement>,如下所示:

const MyButton: React.FC<HTMLAttributes<HTMLButtonElement>> = ({children, ...props}) => {
   return (<button {...props}>{children}</button>) 
}

如果您想添加自己的自定义道具以及扩展道具界面,例如:

interface IMyButtonProps extends React.HTMLAttributes<HTMLButtonElement> {
  customProp: string;
}

const MyButton: React.FC<IMyButtonProps> = props => {
   const {children, customProp, ...rest} = props;

   return <button {...rest}>{children}</button> 
}