【问题标题】:How to style Next.js active link with Styled Components如何使用样式化组件设置 Next.js 活动链接的样式
【发布时间】:2022-01-22 00:36:39
【问题描述】:

我正在尝试将样式添加到带有样式组件的活动链接。

我有一个导航栏,根据当前处于活动状态的链接,相应的链接将添加一个样式

谢谢

import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { bool } from 'prop-types';
import StyledSidebar from '../../styles/header/styled.sidebar'
import StyledLink from '../../styles/header/styled.links'


export default function Sidebar({ open }) {
    const router = useRouter()

    return (
        <StyledSidebar open={open}>
            <div>
                <ul>
                    <StyledLink><Link href="/" className={router.pathname == "/" ? 'active' : ''}>HOME</Link></StyledLink>
                    <StyledLink><Link href="/destination" className={router.pathname == "/destination" ? 'active' : ''}>DESTINATION</Link></StyledLink>
                    <StyledLink><Link href="/crew" className={router.pathname == "/crew" ? 'active' : ''}>CREW</Link></StyledLink>
                    <StyledLink><Link href="/technology" className={router.pathname == "/" ? 'active' : ''}>TECHNOLOGY</Link></StyledLink>
                </ul>
            </div>
        </StyledSidebar>
    )
}

Sidebar.propTypes = {
    open: bool.isRequired,
};


【问题讨论】:

  • HOME 像这样传递它
  • 让我知道这是否有效。我会在回答中详细解释
  • 感谢您的回答。如何使用样式化组件通过此方法更改活动链接的样式?

标签: javascript next.js styled-components


【解决方案1】:

检查此https://codesandbox.io/s/exciting-kilby-eb3pj?file=/src/App.js:0-584 链接,您可以在其中看到此逻辑

将 props 传递给 styled-components 作为普通 props 重组,并使用它来有条件地渲染样式

import styled, { css } from "styled-components";

// props which are received are destructured
const Button = styled.button(
  ({ someprops }) => css`
    ${console.log(someprops)}
    font-size: 1em;
    margin: 1em;
    padding: 0.25em 1em;
    border-radius: 3px;
// Conditionally render the styles inside style
    color: ${someprops === "root" ? "red" : "green"};
    border: 2px solid ${someprops === "root" ? "red" : "green"};
  `
);

export default function App() {
  return (
    <div>
      <Button someprops="root">Themed</Button>
    </div>
  );
}

【讨论】:

  • 差不多了,现在我只需要根据点击的链接添加样式。它适用于一个人,但我需要它适用于所有人。我试过border-right: 3px solid ${props === "/destination" ? "white" : "transparent" } 也是,但它一次只适用于一个。
  • 这是一种您必须对其进行调整才能使其发挥作用的方法。如果可行,请接受作为答案
猜你喜欢
  • 2021-05-09
  • 2021-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-03
  • 1970-01-01
  • 2021-04-21
  • 2021-07-04
相关资源
最近更新 更多