React Router:禁用/停用链接的 3 种方法

这篇简洁实用的文章向您展示了在使用 React Router 6(最新版本)的 React 应用程序中禁用/停用链接的 3 种不同方法。 我们将探索基础知识,然后将它们应用到一个完整的示例中。事不宜迟,让我们开始吧。

三种方法

使用 CSS 指针事件属性

CSS指针事件光标属性指定元素是否对指针事件作出反应。如果它设置为none,则关联的元素(按钮、链接等)在点击时不会执行任何操作。

使用带有指针事件的内联样式的快速示例:

<Link to='/contact' style={{pointerEvents: 'none' }}>
   Contact KindaCode.com
</Link>

以下是我们如何使用单独的 CSS 禁用链接:

<Link to='/contact' className='inactive'>Contact KindaCode.com</Link>

CSS:

.inactive {
  pointer-events: none;
}

使用 event.preventDefault()

我们还可以通过在onClick事件处理函数中调用event.preventDefault() 方法来禁用链接,如下所示:****

// the event handler function
const handleClick = (event) => {
    event.preventDefault();
};

// The Link
<Link to={'/about-us'} onClick={handleClick}>
    About KindaCode.com
</Link>

有条件地渲染 Link 组件

在此方法中,我们将 Link 的禁用/启用状态保存在一个变量中,并使用此变量有条件地呈现 UI:

// state variable
const [isDisabled, setIsDisabled] = useState(true);

// Implement the Link in JSX
<>
  {isDisabled 
       ? <span>This Link is Disabled</span>
       : <Link to="/hello">Hello Buddy</Link>
</>

如果您仍然对所有这些感到不确定,请参阅下面直观的端到端示例,以获得更好的理解。

完整示例

应用预览

我们要制作的演示包含 2 页:

  • 主页
  • 联系页面

在主页上,有一个复选框和 3 个链接(都指向联系人页面)。一开始,这些链接正常工作。但是,当您选中该复选框时,它们将被禁用并且不再工作。下面的动画 GIF 截图清楚地描述了它:

React Router:禁用/停用链接的 3 种方法

步骤

1.新建一个React项目:

npx create-react-app kindacode-example

这个名字完全取决于你。到目前为止,我们只关心一个文件:src/App.js

2.安装反应路由器:

npm i react-router-dom

3. src/App.js的完整源码(附解释):

// KindaCode.com
// src/App.js
import { useState } from 'react';
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path='/' element={<HomePage />} />
        <Route path='/contact' element={<ContactPage />} />
      </Routes>
    </BrowserRouter>
  );
}

// Home Page
const HomePage = () => {
  // this determines if the link is disabled or not
  const [isDisabled, setIsDisabled] = useState(false);

  // this function is triggered when the checkbox is checked/unchecked
  const toggleLink = () => {
    setIsDisabled(!isDisabled);
  };

  return (
    <div style={{ padding: 30 }}>
      <h1>KindaCode.com - Home Page</h1>
      <div>
        <label htmlFor='my-checkbox'>
          <input
            id='my-checkbox'
            type='checkbox'
            value={isDisabled}
            onChange={toggleLink}
          />
          Disable The 3 Links Below
        </label>
      </div>

      {/* Display a message to inform the user about the links */}
      {isDisabled ? (
        <p>
          <strong style={{ color: 'red' }}>All Links are Disabled</strong>
        </p>
      ) : (
        <p>
          <strong style={{ color: 'blue' }}>All Links are Enabled</strong>
        </p>
      )}

      {/* Link 1 - event.preventDefault() */}
      <p>
        <Link
          to={'/contact'}
          onClick={(event) => {
            if (isDisabled) {
              event.preventDefault();
            }
          }}
        >
          Link 1
        </Link>
      </p>

      {/* Link 2 - pointerEvents */}
      <p>
        <Link
          to={'/contact'}
          style={{ pointerEvents: isDisabled ? 'none' : 'auto' }}
        >
          Link 2
        </Link>
      </p>

      {/* Link 3 - conditionally render the working/non-working Link */}
      <p>
        {isDisabled ? <span>Link 3</span> : <Link to={'/contact'}>Link 3</Link>}
      </p>
    </div>
  );
};

// Contact
const ContactPage = () => {
  return (
    <div style={{ padding: 30 }}>
      <h1>Contact KindaCode.com</h1>
    </div>
  );
};

export default App;

4.以开发模式运行项目:

npm start

结论

我们已经介绍了几种禁用 React Router 链接的技术。它们都很整洁,工作良好。选择你喜欢的那个。