reactjs - 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;
解决方案
你有两个选择:要么使用 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}>
推荐阅读
- ios - iPad OS 如何确定 iOS 13 Safari 中的桌面站点是什么
- node.js - Promise 在 NodeJS 中返回 undefined
- path - 根路径规范不再解析为子域
- python-3.x - 使用 `numpy.genfromtxt()` 从 CSV 文件中保存标头
- python - 有人可以向我展示一个不在循环中使用 pysimplegui 的示例 - 也许作为我可以手动更新的定义设置
- c - 是否可以更改用 const 限定符分配的变量的值
- javascript - 如何在谷歌浏览器的输入字段中使用我自己的搜索引擎搜索建议
- reactjs - 如何渲染组件取决于角色
- mysql - Laravel:根据另一个表中的其他数据选择数据
- python-3.x - 语法错误(TypeError:'DataFrame' 对象不可调用)