用 TypeScript 和 css-in-js 的方式写 react app

时间:2021-1-8 作者:admin

Create react app with TypeScript & css-in-js.

Get Started

Init a project:

$ yarn add create-react-app -g

$ create-react-app my-app --scripts-version=react-scripts-ts

$ cd my-app

Adding css-in-js module:

$ yarn add glamorous glamor

Adding style

Creating a style file at ./MyComponent/MyComponent-styles.tsx.

import { CSSProperties } from 'glamorous';
const styles = {
  color: {
    white: '#FFFFFF',
    black: '#000000',
    gray: '#EEE',
  }
}
export const myComponent = (hover: Boolean) => ({
  color: hover ? styles.black : styles.white,
  border: `1px solid ${styles.gray}`,
} as CSSProperties);

Importing style file in your component.

import * as React from 'react';
import glamorous from 'glamorous';
import * as styles from './MyComponent-styles';

const { Div } = glamorous;

interface Props {

}

interface State {
  hovering: Boolean; 
}

export class MyComponent extends React.Component<Props, State> {
  state = {
    hovering: false
  };

  render() {
    return (
      <Div css={styles.myComponent(this.state.hovering)} />
    )
  }
}

Developing

$ yarn start

$ yarn build

There has a problem with glamorous, when you try to give a glamorous Button an onClick attribute with a Function as argument, a error will be display. Just look at this issue.

声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎进行举报,并提供相关证据,工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。