简体   繁体   中英

react put a onChange on <div> , will be triggered when the <input/> in it be changed

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.

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>

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