将 `this` 绑定到 React 组件上的 onClick 事件时会给出 `Parameter 'this' implicitly has an 'any' type` 错误
While binding `this` to onClick event on React component is giving `Parameter 'this' implicitly has an 'any' type` error
P.S。我试过 Whosebug 的其他答案,但不知何故不起作用。
我将 this
绑定到 onClick 函数处理程序,如下所示
const handleUpdatePermissionClick = async (user: UserPermission) => {
try {
await updateUserPermission(user)
setShowError(false)
} catch (e) {
setShowError(true)
}
}
<MenuItem
name={ele.name}
Key={ele.name}
onClick={handleUpdatePermissionClick.bind(this, { permission: ele, userId })}
/>
但它给我 Parameter 'this' implicitly has an 'any' type
错误。
我尝试分配多种类型,即。 any, void,typeof 到 this
as
onClick={handleUpdatePermissionClick.bind(this:any, { permission: ele, userId })}
但是它给出了不需要类型的错误。请帮我解决这个问题。
以下更改对我有用。我没有绑定,而是通过了正常事件。
调用 onClick 处理函数时使用 React.MouseEvent<HTMLElement>
作为事件类型
并且在函数定义中使用“_e”来抑制 param defined but not used
错误。
将其添加到此处以便将来可能对某人有所帮助。
const handleUpdatePermissionClick = async (_e:React.MouseEvent<HTMLElement>,user: UserPermission) => {
try {
await updateUserPermission(user)
setShowError(false)
} catch (e) {
setShowError(true)
}
}
<MenuItem
name={ele.name}
key={ele.name}
onClick={(e: React.MouseEvent<HTMLElement>) => {
handleUpdatePermissionClick(e, { permission: ele, userId })
}}
/>
这可能是上下文造成的。
在 return 之前的渲染中,只需执行以下操作;
让那个=这个;
并使用那个而不是这个来调用函数。
它对我有用。
P.S。我试过 Whosebug 的其他答案,但不知何故不起作用。
我将 this
绑定到 onClick 函数处理程序,如下所示
const handleUpdatePermissionClick = async (user: UserPermission) => {
try {
await updateUserPermission(user)
setShowError(false)
} catch (e) {
setShowError(true)
}
}
<MenuItem
name={ele.name}
Key={ele.name}
onClick={handleUpdatePermissionClick.bind(this, { permission: ele, userId })}
/>
但它给我 Parameter 'this' implicitly has an 'any' type
错误。
我尝试分配多种类型,即。 any, void,typeof 到 this
as
onClick={handleUpdatePermissionClick.bind(this:any, { permission: ele, userId })}
但是它给出了不需要类型的错误。请帮我解决这个问题。
以下更改对我有用。我没有绑定,而是通过了正常事件。
调用 onClick 处理函数时使用 React.MouseEvent<HTMLElement>
作为事件类型
并且在函数定义中使用“_e”来抑制 param defined but not used
错误。
将其添加到此处以便将来可能对某人有所帮助。
const handleUpdatePermissionClick = async (_e:React.MouseEvent<HTMLElement>,user: UserPermission) => {
try {
await updateUserPermission(user)
setShowError(false)
} catch (e) {
setShowError(true)
}
}
<MenuItem
name={ele.name}
key={ele.name}
onClick={(e: React.MouseEvent<HTMLElement>) => {
handleUpdatePermissionClick(e, { permission: ele, userId })
}}
/>
这可能是上下文造成的。 在 return 之前的渲染中,只需执行以下操作; 让那个=这个; 并使用那个而不是这个来调用函数。 它对我有用。