【问题标题】:Paragraph tag blocking my div's onClick handler [closed]阻止我的 div 的 onClick 处理程序的段落标记 [关闭]
【发布时间】:2018-12-07 18:08:36
【问题描述】:

我有一个 <div> 与其子 <p> 的大小相匹配

我正在向我的 div 发送一个 onClick 处理程序,但我无法单击它,因为 <p> 正在阻止它。

我可以将 onClick 处理程序发送到另一个级别,但似乎有办法处理这个问题。

class ExampleParent extends React.Component{
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick(event) {
    console.log(event.target);
  }
  render() {
    <ExampleChild onClick={this.handleClick} />
  }
}

const ExampleChild = (props) => {
  return (
    <div onClick={(event) => props.handleClick(event)}>
      <ExampleGrandchild />
    </div>
  )
}

const ExampleGrandchild = () => {
  return (
    <p>hi</p>
  )
}

【问题讨论】:

  • 请分享代码sn-p
  • 我认为您最好更新您的问题并包含相关的源代码....
  • 请访问help center,使用tour查看内容和How to Ask。做一些研究,搜索关于 SO 的相关主题;如果您遇到困难,请发布您的尝试minimal reproducible example,并注明输入和预期输出。
  • 我在问如何单击

    标签下的

    。示例发布。谢谢

标签: javascript html reactjs


【解决方案1】:

有几种解决方案

添加一些 css 以防止鼠标事件由您的 'p' 处理

p {
  pointer-events: none;
}

为您的 ExampleGrandChild 添加一个“onClick”道具,然后在“p”上捕获 onClick 事件并将其冒泡到父级

const ExampleChild = (props) => {
  return (
    <div onClick={props.handleClick}>
      <ExampleGrandchild handleClick={props.handleClick} />
    </div>
  )
}

const ExampleGrandchild = (props) => {
  return (
    <p onClick={props.handleClick}>hi</p>
  )
}

【讨论】:

    猜你喜欢
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    相关资源
    最近更新 更多