传播事件时如何获取按钮值

时间:2019-05-08 07:01:08

标签: javascript reactjs event-handling

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

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

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

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

2 个答案:

答案 0 :(得分:2)

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

  

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

有关阅读here的更多信息。

答案 1 :(得分:1)

使用event.currentTarget

将属性data-value添加到span。因此,单击获取event.currentTarget.value或event.currentTarget.dataset.value

在处理程序内部这样做

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