样式组件:使用 <S.Name /> 命名约定时共享样式组件

IT技术 reactjs styled-components
2021-05-15 11:43:40

我喜欢在你使用的地方使用样式化组件命名约定<S.SomeName>...</S.SomeName>,但是我遇到了一个问题,我需要导入一个组件的样式,然后还要导入一些共享的样式化组件,但我无法再次将其导入为 S。

这是我的文件夹结构:

src
    ├── api
    │   ├── verb-api.js
    │   └── list-api.js
    ├── axios
    │   └── index.js
    ├── components
    │   └── ListsCard
    │       ├── SubListsCard
    │       │   ├── AnalyticsPage.js
    │       │   ├── VerbsPage.js
    │       │   ├── index.js
    │       │   └── styles.js
    │       ├── index.js
    │       └── styles.js
    ├── hooks
    │   ├── mutations
    │   │   ├── useListMutation
    │   │   └── useVerbMutation
    │   ├── useClickOutside
    │   └── useFocusInput
    ├── routes
    │   ├── Home.js
    │   ├── index.css
    │   └── index.js
    └── index.js

我需要使用来自SubListsCard/styles.jsListsCard/styles.js用于我的 SubListsCard 组件的样式(我可能会创建一个名为 shared 的文件夹从中导入,而不是从 导入ListsCard/styles.js)。

我的解决方案只是将共享样式的组件导入SubListsCard/styles.js并导出:

import styled from "styled-components"
import {SomeComponent, OtherComponent} from "../styles"

export {SomeComponent, OtherComponent}; 

const Name = styled.div`

    ...

`;

有没有更好的方法来做到这一点?

提前致谢 :)

1个回答

我喜欢在https://zzzzbov.com/blag/styled-components-naming-convention 中提到的方法,我喜欢迄今为止我遇到的所有解决方案。

Header.js

import { Component } from "react";
import { Navbar } from "react-bootstrap";
import { $Header } from "./style";

class Header extends Component {
    render() {
        return (
            <$Header>
                <Navbar>
                </Navbar>
            </$Header>
        )
    }
}

export default Header;

style.js

import styled from 'styled-components'; 

export const $Header = styled.header`
    z-index: 1;
`