React Router 6:如何创建自定义后退按钮

这篇实用文章向您展示了如何在使用 React Router 6(最新版本)的 React 应用程序中实现自定义后退按钮。除了浏览器的后退按钮,我们的自定义后退按钮将增加便利性并优化用户体验。

在React Router 6中,我们可以使用Usenavigate Hook通过编程方式导航。要回到上一条路线,您可以按照以下方式进行操作:

const navigate = useNavigate();
navigate(-1);

如果您想返回多个页面,请用**-2**,-3等替换 -1等。现在是时候看到一些真实的代码了。

例子

我们要制作的小型演示项目有 2 页:

  • 主页:此页面提供一个链接,将用户引导至关于页面
  • 关于页面:这包含一个可用于返回首页的蓝色按钮

以下是它的工作原理:

React Router 6:如何创建自定义后退按钮

步骤

1.创建一个新的全新反应项目:

npx create-react-app kindacode-example
  1. 安装React Router Dom:
npm i react-router-dom
  1. 在你的src/App.js 文件中,删除所有默认代码并添加以下内容(您可以在评论中找到详细说明):
// KindaCode.com
// src/App.js
import {
  BrowserRouter,
  Routes,
  Route,
  Link,
  useNavigate,
} from 'react-router-dom';
import './App.css';

// App component
function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path='/' element={<HomePage />} />
        <Route path='/about' element={<AboutPage />} />
      </Routes>
    </BrowserRouter>
  );
}

// Home page
const HomePage = () => {
  return (
    <div className='container'>
      <h1>KindaCode.com - Home Page</h1>
      {/* Use this link to go to the About page */}
      <Link to='/about'>Go to About page</Link>
    </div>
  );
};

// About page
const AboutPage = () => {
  // Use this hook to programmatically navigate to another page
  const navigate = useNavigate();

  // This function is used to navigate to the home page
  // It will be called when the button is clicked
  const goBack = () => {
    navigate(-1);
  };

  return (
    <div className='container'>
      {/* Here's our custom back button */}
      <button onClick={goBack} className='back-button'>
        &larr; Go Back
      </button>
      <h1>About Page</h1>
      <p>
        To go to the home page, you can use either the <b>blue back button</b>{' '}
        or the back button of the browser
      </p>
    </div>
  );
};

export default App;

4.我们项目的重要部分是CSS。用以下方式替换您的src/app.cs.cs.cs .

.container {
    width: 80%;
    margin: 30px auto;
}

.back-button {
    padding: 10px 30px;
    background: #2196f3;
    color: #fff;
    font-weight: bold;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: 0.5s;
}

.back-button:hover {
    background: #0d47a1;
}

5.运行它并检查结果:

npm start

结论

您已经学习了如何使用 React Router 6 制作自定义后退按钮。如果浏览器的后退按钮超出我们的控制范围,我们的自定义后退按钮可以放置在页面上的任何位置,只要它有意义。