简体   繁体   中英

React onClick event triggered clicking the child element

The event gets triggered when I click on the parent element, which has the onClick attribute in it, but also when I click on its child element which has no onClick attribute.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.scss';

function Child(props){
    return(
        <div className='child'
                 style={
                    {
                        left:`${props.place[0]}px`,
                        top: `${props.place[1]}px`
                    }
                 }/>
    );
}   

class App extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            locus:[],
        }

        this.relocate = this.relocate.bind(this);
    }

    componentDidUpdate(){
        console.table(this.state);
    }

    relocate(event){
        this.setState({
            locus:[event.nativeEvent.offsetX, event.nativeEvent.offsetY]
        })
    }

    render(){
        return(
            <div className="parent"
                     onClick={this.relocate}>
                <Child place={this.state.locus} />
            </div>
        );
    }
}

ReactDOM.render(<App />, document.getElementById('root'))

When I click on the parent element the child goes to the vector I just clicked, but when I click on the child element the child goes to some point near the upper left corner (because the coordinates being passed are the offset x and y coordinates of the child element, not the parent's coordinates). I wonder if there is a way to avoid the child element to trigger the onClick event.

The issue you are having here is caused by javascript event bubbling. To fix it you just need prevent the bubbling from happening. To do that add the next code to the child component.

 <Child onClick = {(event) => event.stopPropagation();} place={this.state.locus} />

You can read more about events propagation here https://medium.com/@vsvaibhav2016/event-bubbling-and-event-capturing-in-javascript-6ff38bec30e

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