Reactjs react-如何将DOMAttribute添加到自定义组件?

Reactjs react-如何将DOMAttribute添加到自定义组件?,reactjs,typescript,Reactjs,Typescript,我在typescript中有一个自定义的React组件: const MyButton: React.FC = ({children, ...props}) => { return (<button {...props}>{children}</button>) } 如何修改MyButton以使其接受DOMTattributes?您必须使用HTMLAttributes,如下所示: const MyButton: React.FC<HTMLAttribut

我在typescript中有一个自定义的React组件:

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

如何修改MyButton以使其接受DOMTattributes?

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

const MyButton: React.FC<HTMLAttributes<HTMLButtonElement>> = ({children, ...props}) => {
   return (<button {...props}>{children}</button>) 
}
constmybutton:React.FC=({children,…props})=>{
返回({children})
}
如果您想添加自己的自定义道具,还可以扩展道具界面,如下所示:

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

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

   return <button {...rest}>{children}</button> 
}
接口IMyButtonProps扩展React.HTMLAttributes{
customProp:string;
}
const MyButton:React.FC=props=>{
const{children,customProp,…rest}=props;
返回{children}
}

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

const MyButton: React.FC<HTMLAttributes<HTMLButtonElement>> = ({children, ...props}) => {
   return (<button {...props}>{children}</button>) 
}
constmybutton:React.FC=({children,…props})=>{
返回({children})
}
如果您想添加自己的自定义道具,还可以扩展道具界面,如下所示:

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

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

   return <button {...rest}>{children}</button> 
}
接口IMyButtonProps扩展React.HTMLAttributes{
customProp:string;
}
const MyButton:React.FC=props=>{
const{children,customProp,…rest}=props;
返回{children}
}

谢谢您的回答,尽管我在这个设置中遇到了不同的错误(很长的错误消息,我认为这是关键):键入'{子项:ReactNode;accept?:string |未定义;acceptCharset?:string |未定义;action?:string |未定义;allowFullScreen?:boolean |未定义;allowTransparency?:boolean |未定义;…353更多…;key?:string |…1更多…|未定义;}'不能指定键入'ButtonHTMLAttributes'。对不起,我的错。我编辑了我的帖子,现在应该可以了。使用
HTMLAttributes
而不是
HTMLProps
。这很奇怪,有时一个可以,有时另一个可以。谢谢你用自定义道具的信息扩展了你的答案,这将是我的下一个问题:)感谢answer、 尽管我在这个设置中遇到了不同的错误(非常长的错误消息,我认为这是关键):键入'{子项:ReactNode;accept?:string |未定义;acceptCharset?:string |未定义;action?:string |未定义;allowFullScreen?:boolean |未定义;allowTransparency?:boolean |未定义;…353更多…;key?:string |…1更多…|未定义;}'不可分配给键入'ButtonHTMLAttributes'。抱歉,我的错。我编辑了我的帖子,现在应该可以了。使用
HTMLAttributes
而不是
HTMLProps
。这很奇怪,有时一个可以,有时另一个可以。感谢您用自定义道具的信息扩展您的答案,这将是我的下一个问题:)