在父元素上,我正在尝试处理鼠标和键盘事件。 onMouseUp 事件返回一个触发事件的子元素,而 onKeyUp 返回父元素。
这是我的代码:
<div className={s.editorDesc} tabIndex="1" contentEditable="true" suppressContentEditableWarning="true" ref={(input) => {
this.editorDesc = input;
}} onMouseUp={(e) => {
console.log(e.target);
// this.showControls(e);
}} onKeyUp={(e) => {
if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
console.log(e.target);
// this.showControls(e);
}
}}>
{this.state.controls}
<div>
<p>Description of Article</p>
</div>
</div>
onMouseUp 正在记录 p ,而 onKeyUp 正在记录 div 即可。我想知道这种行为背后的原因,以及如何在 onKeyUp 事件的情况下访问触发事件的子元素。
这是一个工作小提琴:https://jsfiddle.net/reactjs/69z2wepo/
class Hello extends React.Component {
render() {
return <div tabIndex="1" contentEditable="true" suppressContentEditableWarning="true" ref={(input) => {
this.editorDesc = input;
}} onMouseUp={(e) => {
console.log(e.target);
// this.showControls(e);
}} onKeyUp={(e) => {
if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
console.log(e.target);
// this.showControls(e);
}
}}>
<div>
<p>Description of Article</p>
</div>
</div>;
}
}
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>