1. 创建项目

      1. yarn create react-app react-typescript-component --template typescript
    2. 输入快捷键ts -> ts模板

    3. 安装样式库 emotion

    React+TypeScript中使用Emotion

    1. yarn add @emotion/react @emotion/react @emotion/styled
    2. // 引入
    3. /* @jsxImportSource @emotion/react */
    4. import { jsx, css} from '@emotion/react';
    5. import styled from '@emotion/styled';
    6. import React, { useState } from "react";
    7. const Counter: React.FC = () => {
    8. const [count, setCount] = useState(0);
    9. const handleCountClick = () => {
    10. setCount(count + 1);
    11. };
    12. return (
    13. <div>
    14. <h2>{count}</h2>
    15. <button
    16. css={css`
    17. padding: 10px 20px;
    18. background: royalblue;
    19. font-size: 20px;
    20. border: none;
    21. color: white;
    22. `}
    23. onClick={handleCountClick}
    24. >
    25. +
    26. </button>
    27. </div>
    28. );
    29. };
    30. export default Counter;
    1. 绑定事件的方法命名 handle 前缀:handleClick
    2. 安装路由

      1. yarn add @reach/router @type/reach__router
    3. 代码: ```tsx // app.tsx import { Router } from “@reach/router”; import React from “react”; import Counter from “./pages/Counter”;

    const App: React.FC = () => { return ( ); };

    export default App;

    1. ```tsx
    2. // pages/Counter.tsx
    3. /* @jsxImportSource @emotion/react */
    4. import { RouteComponentProps } from "@reach/router";
    5. import React, { useState } from "react";
    6. import Button from "../components/Button";
    7. const Counter: React.FC<RouteComponentProps> = () => {
    8. const [count, setCount] = useState<number>(0);
    9. const handleBtnClick = () => {
    10. setCount(count + 1);
    11. };
    12. return (
    13. <div>
    14. <h2>{count}</h2>
    15. <Button onClick={handleBtnClick}>+</Button>
    16. </div>
    17. );
    18. };
    19. export default Counter;
    1. /* @jsxImportSource @emotion/react */
    2. import { jsx, css } from "@emotion/react";
    3. import styled from "@emotion/styled";
    4. import React, { ReactNode, useState } from "react";
    5. interface Props {
    6. children: ReactNode;
    7. onClick?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
    8. }
    9. const Button: React.FC<Props> = (props) => {
    10. return (
    11. <button
    12. css={css`
    13. padding: 10px 20px;
    14. background: royalblue;
    15. font-size: 20px;
    16. border: none;
    17. color: white;
    18. `}
    19. onClick={props.onClick}
    20. >
    21. {props.children}
    22. </button>
    23. );
    24. };
    25. export default Button;