首页 > 解决方案 > 如何在 React 中的两个按钮之间切换并根据单击的按钮更改 NAvlink 路径

问题描述

我正在尝试在反应中的两个图像之间切换并尝试根据路径更改 Navlink 路由在此处输入图像描述

<button className="lessonTypeButton">
  <img
    src={singleLessonsType}
    alt="singleLessonsType"
    className="packageOne"
    onClick={lessonSelected}
  />
</button>

<br />
<br />
<br />

<button className="lessonTypeButton">
  <img
    src={packageLessons}
    alt="packageLessons"
    className="packageTwo"
    onClick={lessonSelected}
  />
</button>

标签: reactjsroutestoggle

解决方案


您可以拥有href在 URL 中具有路由的属性,

<button className="lessonTypeButton">
    <img
      src={packageLessons}
      alt="packageLessons"
      className="packageTwo"
      onClick={lessonSelected}
      href={/packageLessons}
    />
</button>
<button className="lessonTypeButton">
    <img
      src={singleLessonsType}
      alt="singleLessonsType"
      className="packageOne"
      onClick={lessonSelected}
      href={/singleLessonsType}
    />
</button>

或使用挂钩,

import { useHistory } from "react-router-dom";

然后在函数中使用它,

let history = useHistory();

function lessonSelected = ()=>{
    history.push("/singleLessonsType");
}

或者直接调用 onclick 事件,

<button className="lessonTypeButton">
    <img
      src={packageLessons}
      alt="packageLessons"
      className="packageTwo"
      onClick={history.push("/packageLessons");}
    />
</button>
<button className="lessonTypeButton">
    <img
      src={singleLessonsType}
      alt="singleLessonsType"
      className="packageOne"
      onClick={history.push("/singleLessonsType");}
    />
</button>

推荐阅读