我有一个功能组件
import React, { useState } from 'react'
export default function AboutUs() {
const [counter,setCounter] = useState(0);
const clicked = () => {
setCounter(counter+1);
}
return (
<div>
<p>you clicked {counter} times</p>
<button onClick={clicked}>Click</button>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
这没有任何问题,而且效果很好。但是当我删除按钮元素中的 onClick 并添加事件侦听器时:
import React, { useEffect, useState } from 'react'
export default function AboutUs() {
const [counter,setCounter] = useState(0);
useEffect(()=>{
document.getElementById('test').addEventListener('click',clicked);
},[])
const clicked = () => {
setCounter(counter+1);
}
return (
<div>
<p>you clicked {counter} times</p>
<button id="test">Click</button>
</div>
)
} …Run Code Online (Sandbox Code Playgroud) 我有这个打字稿代码:
const pasteFn = (e: ClipboardEvent) => {
const { clipboardData } = e;
const text = clipboardData?.getData('text/plain');
console.log(text);
};
window.addEventListener('paste', pasteFn);
Run Code Online (Sandbox Code Playgroud)
我疯狂地搜索并尝试了所有示例,但我不明白我得到的错误:
No overload matches this call.
Overload 1 of 2, '(type: keyof WindowEventMap, listener: (this: Window, ev: Event | DeviceMotionEvent | DeviceOrientationEvent | GamepadEvent | ... 23 more ... | StorageEvent) => any, options?: boolean | ... 1 more ... | undefined): void', gave the following error.
Argument of type '"paste"' is not assignable to parameter of type …Run Code Online (Sandbox Code Playgroud)