单击时React防止事件在嵌套组件中冒泡 [英] React prevent event bubbling in nested components on click

查看:470
本文介绍了单击时React防止事件在嵌套组件中冒泡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个基本组成部分. <ul><li>都具有onClick功能.我只希望触发<li>上的onClick,而不希望触发<ul>.我该如何实现?

Here's a basic component. Both the <ul> and <li> have onClick functions. I want only the onClick on the <li> to fire, not the <ul>. How can I achieve this?

我玩过e.preventDefault(),e.​​stopPropagation()都无济于事.

I've played around with e.preventDefault(), e.stopPropagation(), to no avail.

class List extends React.Component {
  constructor(props) {
    super(props);
  }

  handleClick() {
    // do something
  }

  render() {

    return (
      <ul 
        onClick={(e) => {
          console.log('parent');
          this.handleClick();
        }}
      >
        <li 
          onClick={(e) => {
            console.log('child');
            // prevent default? prevent propagation?
            this.handleClick();
          }}
        >
        </li>       
      </ul>
    )
  }
}

// => parent
// => child

推荐答案

我遇到了同样的问题.我发现stopPropagation did 工作正常.我将列表项拆分为一个单独的组件,如下所示:

I had the same issue. I found stopPropagation did work. I would split the list item into a separate component, as so:

class List extends React.Component {
  handleClick = e => {
    // do something
  }

  render() {
    return (
      <ul onClick={this.handleClick}>
        <ListItem onClick={this.handleClick}>Item</ListItem> 
      </ul>
    )
  }
}

class ListItem extends React.Component {
  handleClick = e => {
    e.stopPropagation();  //  <------ Here is the magic
    this.props.onClick();
  }

  render() {
    return (
      <li onClick={this.handleClick}>
        {this.props.children}
      </li>       
    )
  }
}

这篇关于单击时React防止事件在嵌套组件中冒泡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆