简体   繁体   中英

Stop event propagation from input in React

I have two React components. One has a window.onkeyup listener and when for instance space is pressed it performs an action. 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. 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. 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 .

 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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