如何知道 onBeforeInput 和 onInput 的事件是相关的?
export const MyApp = () => {
const onBeforeInput = (eventBefore) => {
console.log(eventBefore)
}
const onInput = (event) => {
console.log(event)
const eventBefore = getEventBefore() // how can i get eventBefore here?
console.log(eventBefore)
}
return (
<textarea onBeforeInput={onBeforeInput} onInput={onInput}/>
);
}
如何在
eventBefore
中使用关联的onInput
?
评论:我问是因为我需要使用
selectionStart
from eventBefore
inside onInput
.
eventBefore
存储在两个函数共有的变量中如果您在包含两个函数的环境中创建变量,它们应该共享一个变量:
export const MyApp = () => {
let theEventBefore = null
const onBeforeInput = (eventBefore) => {
theEventBefore = eventBefore
console.log("theEventBefore being set to:",theEventBefore)
}
const onInput = (event) => {
console.log(event)
console.log("theEventBefore being read as:",theEventBefore)
}
return (
<textarea onBeforeInput={onBeforeInput} onInput={onInput}/>
);
}
beforeInput
将在 onInput
开始之前完成,只要 beforeInput
是同步的Javascript 是单线程的,所以除非你使用 promises 或 async/await 等,否则你可以确定
beforeInput
将首先完成。
Once the
beforeinput
event has completed, the browser will process the user input and then fire the input event.
我发现使用
onKeyDown
比使用 onBeforeInput
更好,因为 onBeforeInput
不会在退格时触发。