【问题标题】:How to use href with onClick() in IonButton?如何在 IonButton 中将 href 与 onClick() 一起使用?
【发布时间】:2021-11-13 04:09:56
【问题描述】:

下面的 onClick() 函数在没有 href 的情况下按预期工作。但是当我添加 href 时,似乎只有 href 运行,而不是 onClick() 函数。如何同时运行 onClick() 函数并将用户发送到新页面?

                <IonButton
                    color="primary"
                    onClick={() => {saveData()}}
                    href="/create/"
                >Save</IonButton>

【问题讨论】:

    标签: reactjs ionic-framework ionic-react


    【解决方案1】:

    你真的不想使用href 使用history

    const history = useHistory();
    
    <IonButton color="primary"
      onClick={(event) => { 
          event.preventDefault();
          saveData(); 
          history.push("/create")}}
    > Save
    </IonButton>
    

    【讨论】:

      【解决方案2】:

      preventDefault() 的 JS 方法 event 将限制 JS 引擎执行 HTML 标记的默认功能,以便在任何事件上执行。在您的情况下,导航到&lt;a&gt; 标记的href 属性中提到的URL。

      在处理程序中调用点击事件的preventDefault,如下所示:

      const history = useHistory();
      
      // ....
      
      const saveData = event => {
        event.preventDefault();
      
        // here you can implement your logic
        history.push("/create");
      }
      

      【讨论】:

      • 所以我更想知道“不”防止默认的最佳方法是同时使用 onClick。现在我只是将 window.location.href 放在 onClick 函数中,但是,也许这没关系?不过,它似乎不太适合 react 或 ionic 框架
      • 因为 ReactJS 是一个 SPA 风格的库。它仅使用静态路由。如果您执行 window.location.href,它将重新加载整个页面。这将是 App.js 的重新渲染。因此,使用 react-router-dom 之类的库,您可以重定向到另一个 React Route,此外,它将使用 Link 组件而不是 标签。
      • 啊,这很有道理,你!
      猜你喜欢
      • 2017-03-24
      • 2019-10-13
      • 2014-08-08
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多