除了拉奥·阿西姆所说的.为了避免重复,将它们作为一个数组,然后对该数组使用.map
.
function Component() {
const pathname = usePathname();
return (
<div className="links">
{[
{ label: "Home", href: "/" },
{ label: "Store", href: "/store" },
{ label: "Actors", href: "/actors" },
].map(({label, href}) => (
<Link
key={label}
href={href}
className={pathname === href ? "active" : ""}
>{label}</Link>
))}
</div>
)}
为了获得更好的可读性,可以将数组声明移出JSX:
function Component() {
const pathname = usePathname();
const navElements = [
{ label: "Home", href: "/" },
{ label: "Store", href: "/store" },
{ label: "Actors", href: "/actors" },
]
return (
<div className="links">
{navElements.map(({label, href}) => (
<Link
key={label}
href={href}
className={pathname === href ? "active" : ""}
>{label}</Link>
))}
</div>
)}