0

this code below, when I input text in input, the onChange function on will run.

Why the onChange on div can run? Where can I find the docs about this?

class App extends Component {
    render() {
        return (
            <div className="App">
                <GiantInput onChange={(e) => console.log('giant onChange', e.target)}/>


                <div onChange={(e) => {
                    console.log('change!', e);
                }}>
                    输入2:<input style={{width: '50%', 'border-color': 'black'}}/>
                </div>
            </div>
        );
    }
}

I meet this problem when I use {...others} = props, the "onChange" function be contained in the others, and put on a div, it make the component call the onChange twice, and I spend lots of time to find why.

Yuiffy
  • 119
  • 1
  • 7
  • Will be helpful for you: [event bubbling and capturing](https://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing) – The Reason Apr 16 '18 at 13:56

1 Answers1

2

This is not about React.js. It is called Event Bubbling.

Use e.stopPropagation() to stop event bubbling.

In your code

<div onChange={e =>console.log('change!', e)}>
      输入2: <input onChange={e => e.stopPropagation()} 
                 style={{width: '50%', 'border-color': 'black'}}/>
</div>
Ritwick Dey
  • 18,464
  • 3
  • 24
  • 37