简体   繁体   English

停止来自 React 输入的事件传播

[英]Stop event propagation from input in React

I have two React components.我有两个 React 组件。 One has a window.onkeyup listener and when for instance space is pressed it performs an action.一个有一个window.onkeyup侦听器,例如当按下空格时它会执行一个动作。 The other has input elements to edit text attributes.另一个具有用于编辑文本属性的输入元素。 However, when the text is edited in the second component the keyevent is also fired in the first component.但是,当在第二个组件中编辑文本时,也会在第一个组件中触发keyevent I have tried adding:我试过添加:

event.stopPropagation()
event.preventDefault()
event.nativeEvent.stopImmediatePropagation()

In the event handler but none of these seems to stop the event.在事件处理程序中,但这些似乎都没有停止事件。

I made a code example, in which case I don't want the window.onkeyup event to fire when typing in the input.我做了一个代码示例,在这种情况下,我不希望在输入时触发window.onkeyup事件。 Is there any way to solve this?有没有办法解决这个问题?

 class Hello extends React.Component { componentDidMount() { window.onkeyup = () => console.log("hello") } handleChange(event) { event.preventDefault() event.nativeEvent.stopImmediatePropagation() } render() { return <div onChange={this.handleChange}><input ></input></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"></div>

You want to use the onKeyUp event instead, and use event.stopPropagation .您想改用onKeyUp事件,并使用event.stopPropagation

 class Hello extends React.Component { componentDidMount() { window.onkeyup = () => console.log("hello"); } handleKeyUp(event) { event.stopPropagation(); } render() { return <div onKeyUp={this.handleKeyUp}><input /></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"></div>

The solution for a similar case where I had an event listener attached to the space button, with input elements on the same page:类似情况的解决方案,我在空格按钮上附加了一个事件侦听器,输入元素位于同一页面上:

In the event listener, if focus is on an input element, return :在事件侦听器中,如果焦点位于输入元素上,则return

const listener = (e) => {
  if (e.target.tagName === "INPUT" || e.target.tagName === "BUTTON"){
    return
  } else {
    if(e.key === " "){
      console.log("Do something");
    }
  }
}

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

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