You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为react-anchor-link-smooth-scroll的AnchorLink组件添加Tailwind CSS样式?

下面提供几种可行的解决方案:

1. 确保Tailwind正确扫描到组件中的类

Tailwind仅会编译它扫描范围内的类,如果你的组件文件不在Tailwind配置的content列表里,对应样式就不会生成。检查tailwind.config.js文件,确保content数组包含你的组件路径:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}", // 覆盖src目录下所有组件文件
  ],
  theme: {
    extend: {
      colors: {
        primary: { 500: '#你的主色值' },
        secondary: { 500: '#你的次色值' },
      },
    },
  },
  plugins: [],
}

修改后重启开发服务器,让Tailwind重新扫描文件。

2. 用容器元素包裹AnchorLink,将样式作用于容器

如果组件未正确将className转发到底层DOM元素,可以在外层添加一个容器,把Tailwind样式应用到容器上,同时设置内部AnchorLink占满容器以保证点击区域完整:

import React from "react";
import AnchorLink from "react-anchor-link-smooth-scroll";
import { SelectedPage } from "./types";

type Props = {
  children: React.ReactNode;
  setSelectedPage: (value: SelectedPage) => void;
};

const ActionButton = ({ children, setSelectedPage }: Props) => {
  return (
    <div className="rounded-md bg-secondary-500 px-10 py-2 hover:bg-primary-500 hover:text-white">
      <AnchorLink
        onClick={() => setSelectedPage(SelectedPage.ContactUs)}
        href={`#${SelectedPage.ContactUs}`}
        className="block w-full h-full"
      >
        {children}
      </AnchorLink>
    </div>
  );
};

export default ActionButton;

3. 替换为自定义平滑滚动链接(不依赖第三方组件)

如果上述方法都无效,可以直接使用原生<a>标签实现平滑滚动,样式会直接生效:

import React from "react";
import { SelectedPage } from "./types";

type Props = {
  children: React.ReactNode;
  setSelectedPage: (value: SelectedPage) => void;
};

const ActionButton = ({ children, setSelectedPage }: Props) => {
  const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
    e.preventDefault();
    setSelectedPage(SelectedPage.ContactUs);
    const targetElement = document.getElementById(SelectedPage.ContactUs);
    targetElement?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  return (
    <a
      href={`#${SelectedPage.ContactUs}`}
      onClick={handleClick}
      className="rounded-md bg-secondary-500 px-10 py-2 hover:bg-primary-500 hover:text-white"
    >
      {children}
    </a>
  );
};

export default ActionButton;

内容的提问来源于stack exchange,提问作者deepak_k_0001

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 21:17:38