스타일이 지정된 구성요소에서 링크의 스타일 활성 상태

5063 단어 reactstyledcomponents

React Router로 ActiveClassName 처리하기

The activeClassName property is used to give a CSS class to an element when it is active. The default given class is active. This will be joined with the className prop, see NavLink Docs . 간단한 구현은 다음과 같습니다.

import { NavLink } from 'react-router-dom';

// ... some other code

<NavLink to="/" activeClassName="selected">
     Home
</NavLink>

<NavLink to="/blog" activeClassName="selected">
     Blog
</NavLink>

<NavLink to="/about" activeClassName="selected">
     About
</NavLink>

selected CSS 클래스를 사용하여 탐색 링크에 다른 스타일을 적용할 수 있습니다.

.selected {
  color: #ff0000; // red
}


활성 경로 스타일에 대한 또 다른 옵션은 activeStyle 에서 NavLink 속성을 사용하는 것입니다. NavLink가 활성 상태일 때 스타일을 적용합니다. 아래 예를 참조하십시오.

<NavLink
  to="/faq"
  activeStyle={{
    fontWeight: 'bold',
    color: #ff0000, // red
  }}
>
  FAQs
</NavLink>


💰: Start your cloud journey with $100 in free credits with DigitalOcean!

스타일 구성 요소 접근 방식

Styled components are visual primitives to style your React App, see github .
activeClassNamereact-router 속성을 사용하려면 세 가지 옵션이 있습니다.
  • 스타일 구성 요소 attrs 방법
  • activeClassName을 styled component prop으로 전달
  • react-router
  • 에서 activeStyle 사용

    .attrs 메서드

    The .attrs method is a chainable method that attaches some props to a styled component. The first and only argument is an object that will be merged into the rest of the component's props. The attrs object accepts the following values:

    export const StyledNavLink = styled(NavLink).attrs({
      activeClassName,
    })`
      &.${activeClassName} {
        color: red;
      }
    `;
    
    <StyledNavLink activeClassName="any" />;
    

    activeClassName 속성 전달

    A Styled Component passes all HTML attributes if it is a simple element, like a div or button or ..., and all props if it is a React Component.

    To get the activeClassName pass it as a prop and get it in the styled component and apply the conditional styles.

    export const StyledLink = styled(NavLink)`
      color: blue;
    
      &.${props => props.activeClassName} {
        color: red;
      }
    `;
    
    <StyledLink activeClassName="any" />;
    

    활성 스타일 사용

    react-router has the activeStyle prop for styling active links.

    const StyledActiveLink = styled(NavLink)`
      color: blue;
    `;
    
    <StyledActiveLink
      activeStyle={{
        color: 'red',
      }}
    ></StyledActiveLink>;
    
    106

    TL;DR 스타일이 지정된 구성 요소에서 activeClassName을 사용하는 세 가지 옵션이 있습니다. 속성 메서드 activeClassName을 소품으로 전달 활성 스타일 사용

    Thanks for reading and if you have any questions , use the comment function or send me a message . If you want to know more about

    참조(그리고 큰 감사):

    React , React Tutorials

    좋은 웹페이지 즐겨찾기