React Router DOM + Flowbite NavBar:链接问题

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

我想将 React Router DOMFlowbite React 一起使用。我正在尝试构建一个导航栏。

import {Link, useLocation} from "react-router-dom";
import {Navbar} from "flowbite-react";
...
const location = useLocation();
...
<Link to="/page">
    <Navbar.Link active={location.pathname === "/page"}>
        Link
    </Navbar.Link>
</Link>

它有效,但我收到警告:

react-dom.development.js:86 Warning: validateDOMNesting(...): <a> cannot appear as a descendant of <a>.

我明白为什么会发生这种情况(因为

Link
Navbar.Link
都包含
<a>
),但我不知道如何修复这些警告。

reactjs react-router-dom tailwind-css flowbite
2个回答
3
投票

我在

useLinkClickHandler
的使用中找到了解决方案:

import {useLinkClickHandler, useLocation} from "react-router-dom";
import {Navbar} from "flowbite-react";

export interface AppNavLinkProps {
    to: string;
    text: string;
}

export default function AppNavLink(props: AppNavLinkProps) {
    const location = useLocation();
    const clickHandler = useLinkClickHandler(props.to);
    
    return <span onClick={clickHandler}>
        <Navbar.Link href={props.to} active={location.pathname === props.to}>
            {props.text}
        </Navbar.Link>
    </span>;
}
...
<AppNavLink to="/page" text="Link" />

这样我就可以去掉

Link
并只保留
Navbar.Link
,但保留
Link
功能(单击链接时不要重新加载页面,而是使用 History API)。


0
投票

as
属性使您能够将 Flowbite 组件转换为另一个组件或 HTML 元素。该 prop 接受一个表示 HTML 标签或功能性 React 组件的字符串。

import {Link, useLocation} from "react-router-dom";
import {Navbar} from "flowbite-react";
...
const location = useLocation();
...
<Link to="/page">
    <Navbar.Link active={location.pathname === "/page"} as="div">
        Link
    </Navbar.Link>
</Link>
© www.soinside.com 2019 - 2024. All rights reserved.