【问题标题】:How to create a button component inside of a react-router Link that does not redirect?如何在不重定向的 react-router Link 内创建一个按钮组件?
【发布时间】:2020-07-01 17:16:11
【问题描述】:

我正在尝试创建一个组件,其中我在整个元素中有一个按钮,它是一个链接,可以将您带到其他地方。

see picture, where entire white block is a link and the button is the lock icon

我见过各种有关使用 e.stopPropagation()e.preventdefault() 的按钮,但似乎都没有用。这就是我现在正在做的事情:

<Link to={`/editAccount/${account._id}`} key={account._id} className="friend displayHorizontallyNoSpaceBetween curveAll transition lightGrayBG">
      <div style={{background: account.color}} className="firstLetter curveLeft centerSelf righteous lightGray">
          {account.account_name[0].toUpperCase()}
      </div>
      <div className="info">
          <h3 className="wordWrap">{account.account_name}</h3>
          <h6>Your account</h6>
      </div>
      <div className="darkGray centerSelf myAccountsFlexEndPrice">
          <IconButton onClick={(event) => {
              event.stopPropagation();
              this.togglePrivacy(event)
          }}> 
              <LockOpenOutlinedIcon style={{ fontSize: 16}} />
          </IconButton>
      </div>
      <div className="myAccountsFlexEndPrice paddingPriceMyAccounts centerSelf darkGray">
          <div className="priceText">
              ${account.total_price.toFixed(2)}
          </div>
                  
      </div>
</Link>

基本上我想要的是IconButton 中的函数,即togglePrivacy(event) 在页面不导航到新链接的情况下被调用。有什么建议吗?

【问题讨论】:

    标签: javascript reactjs react-router react-router-dom preventdefault


    【解决方案1】:

    试试event.preventDefault()。看来您需要将D 大写。

    <IconButton onClick={(event) => {
        event.preventDefault();
        this.togglePrivacy(event);
    }}>
        {...code}
    </IconButton>
    

    【讨论】:

    • 对我不起作用,尝试在回调之前和回调期间包含它。
    • @VictorDanielCardenas 太棒了!!
    猜你喜欢
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多