Skip to content

基于 linaria 的 CSS in JS 方案 #36

@yinxin630

Description

@yinxin630

linaria 可以实现在 JS 中写 CSS, 它是将样式写在模板字符串中赋值给常量, 并通过 babel 插件将其直接编译为静态 css 样式, 常量值即是样式的 class 名, 在 react 中可以直接传递给 className props 来应用样式, 十分方便

优势

  • 常量名即样式 class 名, 对编辑器友好, 比如设置 className 属性时可以补全, cmd + 点击跳转到样式定义位置
  • 常量可以 export 出去, 便于其它组件对其覆盖样式
  • 类似 less / sass 的写法, 学习成本低
  • 组件的样式和逻辑只需要一个文件即可, 便于维护

如何配置

如果你是直接使用的 webpack / rollup 等构建工具, 按照官方 Steup 配置即可

如果你用的是 create-react-app, 推荐使用 cracocraco-linaria

编辑器配置

如果你是 VSCode, 推荐安装 vscode-styled-components 插件, 支持样式补全
image

用法

基础用法

const text = css`
    color: red;
    font-size: 20px;
`;

function App() {
    return (
        <div>
            <p className={text}>应用样式</p>
        </div>
    );
}

子元素选择器

const text = css`
    color: red;
    font-size: 20px;
`;

const container = css`
    .${text} {
        color: blue;
    };
`;

function App() {
    return (
        <div>
            <p className={text}>应用样式</p>
            <div className={container}>
                <p className={text}>子元素选择器</p>
            </div>
        </div>
    );
}

伪类

const li = css`
    color: red;

    &:hover {
        color: blue;
    }
    &:nth-child(2n + 1) {
        background-color: black;
    }
`;

function App() {
    return (
        <div>
            <ul>
                {['111', '222', '333'].map((str) => (
                    <li className={li}>{str}</li>
                ))}
            </ul>
        </div>
    );
}

动画

const diamonds = css`
    width: 200px;
    height: 200px;
    background-color: red;
    animation: spin 2s infinite linear;

    @keyframes spin {
        0% {
            transform: rotate(0);
        }
        100% {
            transform: rotate(360deg);
        }
    }
`;

function App() {
    return (
        <div>
            <div className={diamonds}></div>
        </div>
    );
}

Media Query

const diamonds = css`
    width: 200px;
    height: 200px;
    background-color: red;

    @media (min-width: 1000px) {
        width: 400px;
        height: 400px;
    }
`;

function App() {
    return (
        <div>
            <div className={diamonds}></div>
        </div>
    );
}

全局样式

css`
    :global() {
        body {
            background-color: red;
        }
        p {
            color: blue;
            font-size: 22px;
        }
    }
`;

function App() {
    return (
        <div>
            <p>全局样式</p>
        </div>
    );
}

其它

更多用法请参考 https://github.com/callstack/linaria/blob/master/docs/BASICS.md

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions