如何在 React 中使用 tailwindcss 的平滑滚动?

问题描述 投票:0回答:3

我使用

tailwindcss
React
创建了一个单页网站。在原型中,我使用
tailwindcss
类“scroll-smooth”并且它有效。在
React
中,“scroll-smooth”类不起作用,但原因是什么?

https://tailwindcss.com/docs/scroll-behavior#basic-usage

当我在导航上单击“为什么”时,我跳到“为什么”部分,但不顺利:

function App() {
  return (
    <div className="App">
      <div className="relative">
        <div className="flex flex-col scroll-smooth">

          <HomeNav />

          <HomeHero />

          <section id="why" className="flex flex-col items-center px-6 pt-20">
            ...
          </section>
          <HomeFooter />
        </div>
      </div>
    </div>
  );
}

解决方案:

我认为

TailwindCss
类“滚动平滑”它不适用于反应。所以我使用
NPM
包“react-scroll”,它工作得很好,而且我可能不太担心兼容性。

https://www.npmjs.com/package/react-scroll

reactjs scroll tailwind-css smooth-scrolling
3个回答
12
投票

react-scroll 工作得非常好,但我们仍然可以将

scroll-behavior: smooth
react
tailwindcss
一起使用。这是我的解决方案:


文件夹和文件结构:

App.js

import "./App.css";
import AntyHero from "./components/AntyHero";
import Footer from "./components/Footer";
import Hero from "./components/Hero";
import Navbar from "./components/Navbar";

function App() {
  return (
    <>
      <section id="header">
        <Navbar />
      </section>
      <div className="flex flex-col h-screen items-center justify-center additional gap-3">
        <h1 className="text-5xl">TailwindCSS & React.js</h1>
        <h2 className="text-3xl pb-5">smooth scrolling behavior</h2>
        <div className="flex gap-5 items-center justify-center text-2xl underline bg-white rounded-md p-2">
          <a href="#one" className="text-orange-600">
            Section One
          </a>
          <a href="#two" className="text-red-600">
            Section Two
          </a>
          <a href="#three" className="text-green-700">
            Section Three
          </a>
        </div>
      </div>
      <div className="text-center text-3xl">
        <section id="one" className="h-screen bg-orange-600">
          Section One
        </section>
        <AntyHero />
        <section id="two" className="h-screen bg-red-600">
          Section Two
        </section>
        <Hero />
        <section id="three" className="h-screen bg-green-700">
          Section Three
        </section>
      </div>
      <Footer />
    </>
  );
}

export default App;

index.css

@tailwind base;
html {
  scroll-behavior: smooth;
}

@tailwind components;
@tailwind utilities;

输出

测试使用:“tailwindcss”:“^3.0.11”,“react”:“^17.0.2”Firefox 和 Chrome


5
投票

scroll-behavior: smooth
添加到对我有用的代码中。

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  html {
    scroll-behavior: smooth;
  }
}

0
投票

将“scroll-smooth”添加到 html 标签对我有用。我正在使用 React 和 next.js。

return (
    <html lang="en" className="h-full scroll-smooth">
      ...body
    </html>
  );
© www.soinside.com 2019 - 2024. All rights reserved.