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

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.

原文链接:github.com

上一篇:React:开始构建前你所需的基础知识
下一篇:Electron开发跨平台构建流程设计

相关推荐

公众号

欢迎 JavaScript 爱好者