styled-components allows you to write actual CSS code to style your components. It also removes the mapping between components and styles – using components as a low-level styling construct could not be easier!

優點

這種組件即是元素的方式能讓我們在編寫react元件時看起來更加簡潔,光是少了一堆html元素名稱跟className,就整個看起來簡單好維護

Responsive Styles

General Usage

都可接受函式(function)作為參數、並代入 props 來動態決定樣式

export const StyleList = styled.div`
    background-color: #ccc;
    ul {
        list-style: none;
        li {
            display: flex;
            justify-content: space-between;
            span:before {
                content:'';
                display:inline-block;
                width:10px;
                height: 10px;
                border: 1px solid #000;
                color: ${( props ) => props.color};
            }
        }
    }
`

或改成以下寫法

const getColor = ({ color }) => `color: ${color}`;
const getStyles = ({ color, bg }) => ({
  color,
  background: bg,
});
export const StyleList = styled.div`
    background-color: #ccc;
    ul {
				${getStyles}
        li {
            span:before {
                ${color}
            }
        }
    }
`

Theme Provider

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { ThemeProvider } from 'styled-components';
import Box from './box';
import theme from './theme';

function App() {
  return (
    <ThemeProvider theme={theme}>
      <Box color='white' bg='tomato'>
        Hello World
      </Box>
    </ThemeProvider>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));

box.js

import styled from 'styled-components';
import { color } from 'styled-system';

const Box = styled.div`
  ${color}
  padding: 15px;
  border-radius: 10px;
`;

export default Box;

theme.js

export default {
  colors: {
    white: '#fefefe',
  },
  bg: {
    tomato: 'tomato',
  },
};