【问题标题】:How to stop propagation on Link elements from React-Router-Dom?如何从 React-Router-Dom 停止对 Link 元素的传播?
【发布时间】:2020-07-02 12:23:02
【问题描述】:

我想在来自 React-Router-Dom 的 Link 组件内的事件对象上触发停止传播方法。我的问题是,当我单击 Link 元素内的按钮时,它无论如何都会将我移动到另一个页面。我看到 stopPropagation 方法无法正常工作,Link 元素上的 onClick 事件正在启动。如何防止这种行为?

我在 codeSandbox 上准备了一个示例,但在此示例中,Link 不会将我移动到另一个页面,而只是刷新页面。

示例 https://codesandbox.io/s/serene-surf-h65dz?file=/src/Home.js

我的代码:

const handleClick = e => {
  e.stopPropagation();
  return console.log("Works?");
};

return (
  <Link to={`/edytuj/${item.ID}`} className="table__row">
    <Checkbox
      isSelected={isSelected}
      toggleSelection={() => handleSelection(item, isSelected)}
    ></Checkbox>
    <TableRowItem>{item.ID}</TableRowItem>
    <TableRowItem
      src={item.IMAGE}
      additionalClassName="table__image"
    ></TableRowItem>
    <TableRowItem>{item.NAME}</TableRowItem>
    <TableRowItem>{item.DESCRIPTION}</TableRowItem>
    <TableRowItem additionalClassName="table__cost">
      {item.COST} zł
    </TableRowItem>
    <TableRowItem additionalClassName="table__buttons">
      <Button className="btn btn__edit" icon="fas fa-pen btn__icon">
        Edytuj
      </Button>
      <Button
        onClick={e => handleClick(e)}
        className="btn btn__delete"
        icon="fas fa-times btn__icon"
      >
        Usuń
      </Button>
    </TableRowItem>
  </Link>
);

按钮:

const Button = ({ className, icon, children, onClick }) => {
  return (
    <button onClick={onClick} className={className}>
      {children}
      {icon && <i className={icon}></i>}
    </button>
  );
};

【问题讨论】:

  • 如果您不想导航,链接的目的是什么?你不能用普通的旧div吗?
  • 好的,我修复了... e.preventDefault() 必须在子元素上调用
  • 我确实想导航,但在整行上,里面的 2 个按钮都有自己的动作。在这些按钮之外单击会将您转到另一个页面

标签: javascript reactjs react-router


【解决方案1】:

只需使用 e.preventDefault();

const handleClick = (e) => {
    e.preventDefault();
    return console.log("It works");
  };

https://codesandbox.io/s/small-bird-65zgb?file=/src/Home.js

【讨论】:

  • The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. 在这种情况下,我们有一个“本机” html 事件(或至少在 JS 中模拟),因此我们想要取消默认操作。来源:w3schools.com/jsref/event_stoppropagation.aspw3schools.com/jsref/event_preventdefault.asp
猜你喜欢
  • 2021-05-07
  • 2020-04-24
  • 1970-01-01
  • 2022-01-23
  • 2021-01-28
  • 1970-01-01
  • 2019-11-25
  • 2020-04-29
  • 1970-01-01
相关资源
最近更新 更多