建立在 Styled Jss 下,開始來建立我們組件吧。

目前有三個樣式,filled, outline, text。我們將透過切換 type 的方式來實作,以下是上次的組件範例,接下來我們要開始擴充:
原本程式碼如下:
const Button = styled('input')(({theme}) => ({
    paddingTop: theme.getSpacing(1),
    paddingLeft: theme.getSpacing(2),
    paddingRight: theme.getSpacing(2),
    paddingBottom: theme.getSpacing(1),
    marginTop: theme.getSpacing(2),
    backgroundColor: theme.colors.primary,
}));
Button.propTypes = {
  value: propTypes.string,
  onClick: propTypes.func,
};
Button.defaultProps = {
  value: "",
  onClick: () => false,
};
export default Button;
利用 Stlyed jss 切出三種樣式
import styled from 'styled-jss'
import propTypes from "prop-types";
// 基本樣式
const basicStyle = (theme) => ({
  border: 'none',
  outline: 'none',
  borderRadius: theme.radius,
  paddingTop: theme.getSpacing(1),
  paddingLeft: theme.getSpacing(2),
  paddingRight: theme.getSpacing(2),
  paddingBottom: theme.getSpacing(1),
});
const textStyle = (theme) => ({
  color: theme.colors.primary,
  backgroundColor: theme.colors.transparent,
});
const filledStyle = (theme) => ({
  color: theme.colors.white,
  backgroundColor: theme.colors.primary,
});
const outlineStyle = (theme) => ({
  color: theme.colors.primary,
  border: `1px solid ${theme.colors.primary}`,
  backgroundColor: theme.colors.transparent,
});
const switchTheme = (theme, type) => {
  switch (type) {
    case 'outline':
      return outlineStyle(theme);
    case 'text':
      return textStyle(theme);
    case 'filled':
    default:
      return filledStyle(theme);
  }
}
// 傳入 style 讓使用者客製化
const Button = styled('button')(({ theme, type, style }) => ({
  ...basicStyle(theme),
  ...switchTheme(theme, type),
  ...style,
}));
Button.propTypes = {
  value: propTypes.string,
  onClick: propTypes.func,
  style: propTypes.object,
  type: propTypes.oneOfType(['filled', 'outline', 'text']),
};
Button.defaultProps = {
  value: "",
  type: 'filled',
  style: {},
  onClick: () => false,
};
export default Button;
使用方式
import React, { Fragment } from 'react';
import './App.css';
import theme from './lib/theme';
import Button from './lib/Button';
import { ThemeProvider } from 'styled-jss';
const styles = {
  button: {
    marginRight: 8
  }
}
function App() {
  return (
    <div className="App">
      <ThemeProvider theme={theme}>
        <Fragment>
          <Button type='filled' style={styles.button}>Filled Button</Button>
          <Button type='outline' style={styles.button}>Outline Button</Button>
          <Button type='text' style={styles.button}>Text Button</Button>
        </Fragment>
      </ThemeProvider>
    </div>
  );
}
export default App;
成果如下圖:

利用 Styled jss 來切分組件感覺可以分得滿乾淨的,之後會開始一步一步實作所以的組件。