React prevent event bubbling in nested components on click

前端 未结 8 1512
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 02:41

Here\'s a basic component. Both the

    and
  • have onClick functions. I want only the onClick on the
  • to fir
8条回答
  •  北海茫月
    2020-11-27 03:19

    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 (
          
      Item
    ) } } class ListItem extends React.Component { handleClick = e => { e.stopPropagation(); // <------ Here is the magic this.props.onClick(); } render() { return (
  • {this.props.children}
  • ) } }

提交回复
热议问题