【问题标题】:How to get button value when event is propagated传播事件时如何获取按钮值
【发布时间】:2019-05-08 07:01:07
【问题描述】:

我正在制作一个反应按钮组件,组件看起来像这样

const Button = props => {
  return (
    <button
      style={props.style}
      onClick={props.onClick}
      className={`btn ${props.color} ${props.loading &&
        "loading"} ${props.block && "block"} ${props.className}`}
      disabled={props.disabled}
      type={props.type}
      value={props.value}
    >
      <span className={"content"}>
        {props.icon && <span className={"icon-left"}>{props.icon}</span>}
        {props.children}
      </span>
      {props.loading ? <Spinner /> : null}
    </button>
  );
};

当我尝试向按钮组件添加值道具和事件侦听器时,就会出现问题。 如果我这样做并尝试从 onClick 处理程序中获取 event.target.value 值,则只有当我单击按钮的其他部分时它才会起作用,单击跨度文本会返回 undefined

这似乎是合乎逻辑的,因为跨度没有任何价值,我可以用来解决这个问题的最佳方法是什么?

【问题讨论】:

  • span的onclick可以触发按钮的onclick
  • 向 span 添加一些属性,将 button 的值设置为该属性并使用:e.target.getAttribute
  • event.target.value 不会为 button/span 元素返回任何值,因为这些元素中没有 value 属性。所以尝试一些类似 event.target.name

标签: javascript reactjs event-handling


【解决方案1】:

您应该使用event.currentTarget 而不是event.target

currentTarget 事件属性返回其事件的元素 监听器触发了事件。

更多关于阅读here

【讨论】:

    【解决方案2】:

    使用event.currentTarget

    将属性data-value 添加到span。所以点击获取 event.currentTarget.value 或event.currentTarget.dataset.value

    在处理程序内部这样做

     let m = event.currentTarget.value? 
             event.currentTarget.value:
             event.currentTarget.dataset.value
    

    【讨论】:

    • 谢谢,不知道事件对象中有 currentTarget 属性
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 2021-09-12
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多