首页 > 解决方案 > React Js 中的路由

问题描述

我有两个组件,一个是 Main.js 和 Search.js 我想链接 Main.js 中的按钮以导航到 Search.js,但我不知道该怎么做。

import React from "react";
import classes from "./Main.module.css";
import Aux from "../../hoc/Aux";
import logo from "../../containers/img/Logo.png";
import Search from "../Search/Search";
import { Route } from "react-router-dom";
const Main = () => {
  return (
    <Aux>
      {/* Section starts */}
      <section className={classes.Showcase}>
        {/* Section Left */}
        <div className={classes.ShowcaseLeft}>
          <div className={classes.ShowcaseLeftTop}></div>
          <div className={classes.ShowcaseLeftBottom}></div>
        </div>
        {/* Section Right */}
        <div className={classes.ShowcaseRight}>
          <div className={classes.ShowcaseRightTop}></div>
          <div className={classes.ShowcaseRightRest}>
            <img src={logo} alt="Logo" />
            <p>
              Provide weather, water, and climate data, forecasts and warnings
              for the protection of life and property and enhancement of the
              national economy.
            </p>
            <Route path="/auth" component={Search} />
          </div>
        </div>
      </section>
    </Aux>
  );
};
export default Main;

标签: reactjsreact-router-dom

解决方案


你有两个选择:要么使用 react-router-domuseHistory钩子,要么使用 Link 组件。这里有两种方法:

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

function Main() {
  let history = useHistory();
  return (
    <button type="button" onClick={()=> history.push("/search")}>
      search
    </button>
  );
}

// Link
import { Link } from "react-router-dom";

function Main() {
  let history = useHistory();
  return (
  <Link to="/search">
    <button type="button">
      search
    </button>
  </Link>
  );
}

最后一条建议:我建议将所有路径添加到一个文件中,这样你就永远不会出现任何错字。最后,理想的写法是:<Link to={path.search}>


推荐阅读