简体   繁体   English

为什么 onKeyDown 和 onKeyUp 在附加到 contenteditable div 中的 span 时不会触发?

[英]Why doesn't onKeyDown and onKeyUp fire when attached to a span within a contenteditable div?

here is a code snippet demonstrating the problem:这是一个演示问题的代码片段:

import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
  render() {
    return (
     <div contentEditable="true">
       <p>
         <span onKeyDown={(e)=>{
           alert("hello world!!")
          }}>Hello world</span>
       </p>
     </div>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
);

After focusing on the div and pressing some buttons, the alert is not triggered.关注 div 并按下一些按钮后,不会触发警报。 Why?为什么?

https://codesandbox.io/embed/react-playground-forked-fymxg3?fontsize=14&hidenavigation=1&theme=dark https://codesandbox.io/embed/react-playground-forked-fymxg3?fontsize=14&hidenavigation=1&theme=dark

The content of contenteditable element is treated as user input, not being part of the DOM. contenteditable元素的内容被视为用户输入,而不是 DOM 的一部分。 Same as text in the <input> element.<input>元素中的文本相同。

Thus, you cannot interact with value of that element as you do with normal DOM - meaning no event handlers for you here.因此,您不能像使用普通 DOM 那样与该元素的值进行交互——这意味着这里没有适合您的事件处理程序。

I've faced the same issue.我遇到了同样的问题。

However, we can add listener of clicks by all the children of the contenteditable parent.但是,我们可以添加contenteditable父级的所有子级的点击监听器。

Since someone who want to edit text of a child first click it, we can temporary "store" the child and then we know which child text is edited.由于想要编辑子文本的人首先单击它,我们可以临时“存储”子文本,然后我们知道编辑了哪个子文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM