简体   繁体   English

按钮传递Onclick事件

[英]Button Pass Onclick Event

I have a button.tsx with a onClick property. 我有一个具有onClick属性的button.tsx。

import * as React from 'react';
interface Props {
 className?: string;
 text: string;
 onClick?(event: React.MouseEvent<HTMLButtonElement>): void;
 type?: string;
}
const submitButton = (event: React.MouseEvent<HTMLButtonElement> , props: 
Props) => {
 event.preventDefault();
 props.onClick(event);
};
export const ButtonComponent = (props: Props) => {
 return (
  <button
   className={props.className}
   type={props.type}
   onClick={submitButton(event, props)}
  >
  {props.text}
 </button>
 );
};

How can I pass the event to submitButton function? 如何将事件传递给SubmitButton函数?

Now I have this error: 现在我有这个错误:

Argument of type 'Event' is not assignable to parameter of type 'MouseEvent'. “事件”类型的参数不能分配给“鼠标事件”类型的参数。 Property 'altKey' is missing in type 'Event'. 类型“事件”中缺少属性“ altKey”。

You are calling submitButton immediately during the render rather than passing the function as a handler, therefore event does not exist and you are passing nothing (the return type of submitButton to onClick) 您在渲染过程中立即调用了submitButton ,而不是将函数作为处理函数传递,因此事件不存在,并且您不传递任何内容( submitButton的返回类型为onClick)

Pass as a function to onClick instead 作为函数传递给onClick

<button className={props.className}
        type={props.type}
        onClick={event => submitButton(event, props)}>
  {props.text}
</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM