【问题标题】:<Link to=> not switching pages<Link to=> 不切换页面
【发布时间】:2022-02-11 03:02:55
【问题描述】:

我已经在这个下拉菜单上工作了一段时间,但我似乎无法使用下拉菜单来更改我所在的页面,而且我不明白它有什么问题我对 ReactJs 真的很陌生,我有一个名为 DropDownMenu 的模块,它正在调用 DropDownItem 并且当单击 DropDownItem 时,称为句柄单击的函数,但在 HandleClick 它没有将页面切换到当前点击的 Props.Route 并且我不知道发生了什么来真正弄清楚

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

function DropdownItem(props) {
  const handleClick = () => {
    <Link to={props.route}></Link>;
    console.log(props.route);
  };

  return (
    <a href="#" className="menu-item" onClick={handleClick}>
      <span className="icon-button">{props.leftIcon}</span>
      <span className="Route">{props.route}</span>

      {props.children}
      <span className="icon-right">{props.rightIcon}</span>
    </a>
  );
}

export default DropdownItem;

【问题讨论】:

    标签: html node.js reactjs module


    【解决方案1】:

    您不能只是在回调函数中间抛出一个&lt;Link&gt; 并期望它在被调用时执行任何操作。

    使用&lt;Link&gt; 元素代替 &lt;a&gt; 元素。


    如果您需要从回调触发导航(在这种情况下不需要),请使用 useNavigate

    【讨论】:

      【解决方案2】:

      您可以使用 useHistory 钩子。您可以使用它来导航。

      当你使用 react router dom v5 时

            import { useHistory } from "react-router-dom";
      
           let history = useHistory();
           const handleClick = () => {
              history.push(`/${props.route}`);
              console.log(props.route);
            };
      

      当你使用 react router dom v5 时

      从“react-router-dom”导入 { useHistory };

            const navigate = useNavigate();
           const handleClick = () => {
             navigate(`../${props.route}`, { replace: true });
              console.log(props.route);
            };
      

      【讨论】:

      猜你喜欢
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      • 2020-04-11
      • 2013-08-17
      • 2021-03-15
      • 1970-01-01
      • 2022-01-25
      • 2019-04-24
      相关资源
      最近更新 更多