天天看點

CSS in JS之React-Emotion

​emotion​

​ 是一個 JavaScript庫 ,使用 ​

​emotion​

​​ 可以用寫 js 的方式寫 css 代碼(​​CSS in JS​​)。

在react中安裝emotion後,可以很友善進行css的 封裝,複用。

使用emotion後,浏覽器渲染出來的标簽是會加上一個css開頭的辨別。如下:截圖中以​

​css-​

​開頭的幾個标簽,就是使用emotion庫後渲染出來的。

CSS in JS之React-Emotion

安裝

安裝兩個庫:

​yarn add @emotion/react​

​​

​yarn add @emotion/styled​

使用

1. 引入emotion

import styled from "@emotion/styled";      

2. 建立css元件

// 使用emotion 建立css元件
const Container = styled.div`
display: flex;
flex-direction: column;
align-items: center;
min-height: 100vh;
`;      

3. 在html代碼中使用css元件

<Container>
// html代碼
</Container>      

執行個體

/** @jsxImportSource @emotion/react */
import React from 'react';
import styled from "@emotion/styled"; // 1.引入emotion
import './App.css';

function App() {
    // 3.提取公共的css元件
    const BgColor = styled.div<{ color?: string }>`
        background-color:${props => props.color ? props.color : 'initial'} ;
    `
    const MyBorder = styled.div<{ border?: string }>`
        border:${props => props.border ? props.border + ' solid' : 'none'} ;
    `

    // 2.使用emotion 建立css元件
    const Container = styled.div`
        display: grid;
        grid-template-rows: 5rem 1fr 5rem;
        grid-template-columns: 10rem 1fr 10rem;
        grid-template-areas: 
            'header header header'
            'nav main aside'
            'footer footer footer'
        ;
        height: 100vh;
    `
    const Header = styled(BgColor)`grid-area:header`;
    const Nav = styled.nav`grid-area:nav`;
    const Main = styled(MyBorder)`grid-area:main`;
    const Aside = styled.aside`grid-area:aside`;
    const Footer = styled(BgColor)`grid-area:footer`;

    return (
        <div className="App">
            {/* 4.在html代碼中使用css元件 */}
            <Container>
                <Header color={'#aaa'} as='header'>header</Header>
                <Nav>nav</Nav>
                <Main border={'1px red'} as='main'>
                    <div css={{ backgroundColor: "#ccc" }}>main</div>{/* emotion行内樣式 */}
                </Main>
                <Aside>aside</Aside>
                <Footer color={'#eee'} as='footer'>footer</Footer>
            </Container>
        </div>
    );
}

export default App;