[英]Typescript onclick function in React JS
I have this code in my react js application:我的反应 js 应用程序中有这段代码:
<button onClick={tes} type="button">click</button>
and this is my tes
function:这是我的测试
tes
:
const tes = (id: string) => {
console.log(id)
}
If i hover over onClick
function TS engine return:如果我 hover 超过
onClick
function TS 引擎返回:
TS2322: Type '(id: string) => void' is not assignable to type 'MouseEventHandler<HTMLButtonElement>'. Types of parameters 'id' and 'event' are incompatible. Type 'MouseEvent<HTMLButtonElement, MouseEvent>' is not assignable to type 'string'.
Question: How to fix this and to add correct types?问题:如何解决这个问题并添加正确的类型?
You can't control the type of event that is passed as a parameter to the onClick handler function.您无法控制作为参数传递给 onClick 处理程序 function 的事件类型。 But you can use a dummy middleware function and call your custom handler with a custom parameter by doing something like this:
但是您可以使用虚拟中间件 function 并通过执行以下操作使用自定义参数调用您的自定义处理程序:
<button onClick={() => tes("myid")} type="button">click</button>
const tes = (id: string) => {
console.log(id)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.