繁体   English   中英

React onClick 事件触发点击子元素

[英]React onClick event triggered clicking the child element

当我单击具有 onClick 属性的父元素以及单击其没有 onClick 属性的子元素时,会触发该事件。

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'))

当我单击父元素时,子元素会转到我刚刚单击的向量,但是当我单击子元素时,子元素会转到左上角附近的某个点(因为传递的坐标是偏移量的 x 和 y 坐标)子元素,而不是父元素的坐标)。 想知道有没有办法避免子元素触发onClick事件。

您在这里遇到的问题是由 javascript 事件冒泡引起的。 要修复它,您只需要防止冒泡发生。 为此,将下一个代码添加到子组件中。

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

您可以在此处阅读有关事件传播的更多信息https://medium.com/@vsvaibhav2016/event-bubbling-and-event-capturing-in-javascript-6ff38bec30e

暂无
暂无

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

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