我有一个带有 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>
);
};
如何将事件传递给submitButton函数?
现在我遇到了这个错误:
“Event”类型的参数不可分配给类型的参数 '鼠标事件'。 “事件”类型中缺少属性“altKey”。
最佳答案
您在渲染期间立即调用 submitButton
而不是将函数作为处理程序传递,因此事件不存在并且您没有传递任何内容(submitButton
的返回类型到 onClick)
作为函数传递给 onClick
<button className={props.className}
type={props.type}
onClick={event => submitButton(event, props)}>
{props.text}
</button>
关于javascript - 按钮传递 Onclick 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48278480/