这是一个基本组件。<ul>和<li>都有onClick函数。我只想在<li>上的onClick来触发,而不是<ul>。我怎样才能做到这一点呢?

我已经玩了e.preventDefault(), e.stopPropagation(),没有任何效果。

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确实有用。我将把列表项拆分为一个单独的组件,如下所示:

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

其他回答

我也有同样的问题。我发现stopPropagation确实有用。我将把列表项拆分为一个单独的组件,如下所示:

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

这是一种简单的方法,可以防止单击事件向前移动到下一个组件,然后调用你的yourFunction。

<Button onClick={(e)=> {e.stopPropagation(); yourFunction(someParam)}}>Delete</Button>

如果希望发生嵌套元素中的操作而不是父元素中的操作,则可以从父元素的操作处理程序中检查目标的类型,然后根据该类型执行操作,也就是说,如果目标是嵌套元素,则不执行任何操作。否则两个处理程序都将被调用。

// Handler of the parent element. Let's assume the nested element is a checkbox
function handleSingleSelection(e) {
    if(e.target.type !== 'checkbox') {
        // We do not do anything from the 
        // parent handler if the target is a checkbox ( our nested element)
        // Note that the target will always be the nested element
        dispatch(lineSelectionSingle({ line }))
    }
}

React在文档中使用事件委托和单个事件监听器来处理冒泡事件,比如本例中的'click',这意味着停止传播是不可能的;当你在React中与它交互时,真实的事件已经传播了。在React的合成事件上stopPropagation是可能的,因为React在内部处理合成事件的传播。

stopPropagation: function(e){
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
}

新的方法更简单,会节省你一些时间!只需将事件传递给原始的单击处理程序并调用preventDefault();。

clickHandler(e){
    e.preventDefault();
    //Your functionality here
}