如果单击嵌套元素,请勿调用函数

时间:2019-01-07 13:36:55

标签: javascript reactjs

我有一个带有嵌套组件的组件,像这样:

<div id="bla" onClick={() => this.handleOnClick(this.props.someParameter, this.state.someState, {id})}>
    <div class="wrapper">
    <ChildComponent />
    </div>
    ....

从技术上讲,嵌套组件是一个图标,它具有自己的handleOnClick函数。

如果单击子组件图标,则两个handleOnClick函数都会被调用。但是我只想调用子组件的功能。有没有办法做到这一点?

3 个答案:

答案 0 :(得分:2)

You should use event#stopPropagation.

On your child component's handleOnClick function, just call it like:

handleOnClick = function(e) {
    e.stopPropagation();
    ...rest of your code
} 

I haven't worked with react, but this should work.

答案 1 :(得分:2)

在子组件的event.stopPropagation();函数中使用onClick将解决您的问题。

parameterized SQL query将阻止事件传播到您的父组件

childOnClick = event => {
    event.stopPropagation();
    //.... your code
}

答案 2 :(得分:2)

In your child component event handler, make sure you stop the event from propagating so it doesn't bubbles up to the parent div by calling event.stopPropagation()

class ChildComponent extends React {

  handleChange(event) {
    event.stopPropagation();
  }

  render() {
    return (
        <div>
        <button onClick={this.handleChange}></button>
       </div>
    );
  }
}