# ts在react中的使用

# 组件 Props

先看几种定义 Props 经常用到的类型:

# 基础类型

type BasicProps = {
  message: string;
  count: number;
  disabled: boolean;
  /** 数组类型 */
  names: string[];
  /** 用「联合类型」限制为下面两种「字符串字面量」类型 */
  status: "waiting" | "success";
};
1
2
3
4
5
6
7
8
9

# 对象类型

type ObjectOrArrayProps = {
  /** 如果你不需要用到具体的属性 可以这样模糊规定是个对象 ❌ 不推荐 */
  obj: object;
  obj2: {}; // 同上
  /** 拥有具体属性的对象类型 ✅ 推荐 */
  obj3: {
    id: string;
    title: string;
  };
  /** 对象数组 😁 常用 */
  objArr: {
    id: string;
    title: string;
  }[];
  /** key 可以为任意 string,值限制为 MyTypeHere 类型 */
  dict1: {
    [key: string]: MyTypeHere;
  };
  dict2: Record<string, MyTypeHere>; // 基本上和 dict1 相同,用了 TS 内置的 Record 类型。
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 函数类型

type FunctionProps = {
  /** 任意的函数类型 ❌ 不推荐 不能规定参数以及返回值类型 */
  onSomething: Function;
  /** 没有参数的函数 不需要返回值 😁 常用 */
  onClick: () => void;
  /** 带函数的参数 😁 非常常用 */
  onChange: (id: number) => void;
  /** 另一种函数语法 参数是 React 的按钮事件 😁 非常常用 */
  onClick(event: React.MouseEvent<HTMLButtonElement>): void;
  /** 可选参数类型 😁 非常常用 */
  optional?: OptionalType;
}
1
2
3
4
5
6
7
8
9
10
11
12

# React 相关类型

interface AppProps {
  children1: JSX.Element; // ❌ 不推荐 没有考虑数组
  children2: JSX.Element | JSX.Element[]; // ❌ 不推荐 没有考虑字符串 children
  children4: React.ReactChild[]; // 稍微好点 但是没考虑 null
  children: React.ReactNode; // ✅ 包含所有 children 情况
  functionChildren: (name: string) => React.ReactNode; // ✅ 返回 React 节点的函数
  style?: React.CSSProperties; // ✅ 推荐 在内联 style 时使用
  // ✅ 推荐原生 button 标签自带的所有 props 类型
  // 也可以在泛型的位置传入组件 提取组件的 Props 类型
  props: React.ComponentProps<"button">;
  // ✅ 推荐 利用上一步的做法 再进一步的提取出原生的 onClick 函数类型 
  // 此时函数的第一个参数会自动推断为 React 的点击事件类型
  onClickButton:React.ComponentProps<"button">["onClick"]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# antd

react项目因为经常用到antd

import React from "react"
import { Form, Icon, Input, Button } from 'antd';
import { WrappedFormUtils } from "antd/lib/form/Form"

interface FormFields {
    username: string,
    password: string
}

interface Props {
    form: WrappedFormUtils<FormFields>
}

class LoginForm extends React.Component<Props> {
    handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
            }
        });
    };

    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form onSubmit={this.handleSubmit} className="login-form">
                <Form.Item>
                    {getFieldDecorator('username', {
                        rules: [{ required: true, message: '请输入用户名!' }],
                    })(
                        <Input
                            prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            placeholder="Username"
                        />,
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('password', {
                        rules: [{ required: true, message: '请输入登录密码!' }],
                    })(
                        <Input
                            prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            type="password"
                            placeholder="Password"
                        />,
                    )}
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit" className="login-form-button">
                        登陆
                        </Button>
                </Form.Item>
            </Form>
        );
    }
}

const WrappedLoginForm = Form.create()(LoginForm);

export default WrappedLoginForm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

WrappedFormUtils类型我们是怎么知道的呢?

  1. 用多了就知道了

  2. 网上搜一下

  3. 按住Ctrl左键点击Form组件,此时我们就进入了Form.d.ts文件中

export declare type ValidateCallback<V> = (errors: any, values: V) => void;
export declare type WrappedFormUtils<V = any> = {
    /** 获取一组输入控件的值,如不传入参数,则获取全部组件的值 */
   validateFields(options: ValidateFieldsOptions, callback: ValidateCallback<V>): void;
   //...

};

export interface FormComponentProps<V = any> extends WrappedFormInternalProps<V>, RcBaseFormProps {
    form: WrappedFormUtils<V>;
}
1
2
3
4
5
6
7
8
9
10
11

我们就看到这两句,那么我们就清楚了form应该用的类型了。 同时看到 WrappedFormUtils<V>有一个V泛型,然后传递给了validateFields的参数中的callback:ValidateCallback<V>。export declare type ValidateCallback<V> = (errors: any, values: V) => void;这句话中我看到又传递给了values。因此我们才有上面的

interface FormFields {
    username: string,
    password: string
}

interface Props {
    form: WrappedFormUtils<FormFields>
}
1
2
3
4
5
6
7
8

# 类组件中使用

# 使用props类型

interface FormFields {
    username: string,
    password: string
}

interface Props {
    form: WrappedFormUtils<FormFields>
}

class LoginForm extends React.Component<Props> {
    render() {
        return (
            <div className="login-page">
            </div>
        );
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 使用state类型

interface CourseItem {
    title: string;
    count: number;
}

interface DataStructure {
    [key: string]: CourseItem[];
}

interface State {
    loaded: boolean;
    isLogin: boolean;
    data: DataStructure;
}

class Home extends Component {
    state: State = {
        loaded: false,
        isLogin: true,
        data: {}
    };
    render() {
        
        return <div  />;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

# 函数式组件

# 最简单

interface AppProps = { message: string };

const App = ({ message }: AppProps) => <div>{message}</div>;
1
2
3

# 包含 children 的

利用 React.FC 内置类型的话,不光会包含你定义的 AppProps 还会自动加上一个 children 类型,以及其他组件上会出现的类型:

// 等同于
AppProps & { 
  children: React.ReactNode 
  propTypes?: WeakValidationMap<P>;
  contextTypes?: ValidationMap<any>;
  defaultProps?: Partial<P>;
  displayName?: string;
}

// 使用
interface AppProps  { message: string };

const App: React.FC<AppProps> = ({ message, children }) => {
  return (
    <>
     {children}
     <div>{message}</div>
    </>
  )
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# Hooks

@types/react 包在 16.8 以上的版本开始对 Hooks 的支持。

# useState

const [user, setUser] = React.useState<IUser | null>(null);

// later...
setUser(newUser);
1
2
3
4

# useRef

这个 Hook 在很多时候是没有初始值的,这样可以声明返回对象中 current 属性的类型:

const ref2 = useRef<HTMLElement>(null);
1

# forwardRef

函数式组件默认不可以加 ref,它不像类组件那样有自己的实例。这个 API 一般是函数式组件用来接收父组件传来的 ref。

所以需要标注好实例类型,也就是父组件通过 ref 可以拿到什么样类型的值。

type Props = { };
export type Ref = HTMLButtonElement;
export const FancyButton = React.forwardRef<Ref, Props>((props, ref) => (
  <button ref={ref} className="MyClassName">
    {props.children}
  </button>
));
1
2
3
4
5
6
7

# useReducer

需要用 Discriminated Unions (opens new window) 来标注 Action 的类型。

const initialState = { count: 0 };

type ACTIONTYPE =
  | { type: "increment"; payload: number }
  | { type: "decrement"; payload: string };

function reducer(state: typeof initialState, action: ACTIONTYPE) {
  switch (action.type) {
    case "increment":
      return { count: state.count + action.payload };
    case "decrement":
      return { count: state.count - Number(action.payload) };
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = React.useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "decrement", payload: "5" })}>
        -
      </button>
      <button onClick={() => dispatch({ type: "increment", payload: 5 })}>
        +
      </button>
    </>
  );
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

# useEffect

这里主要需要注意的是,useEffect 传入的函数,它的返回值要么是一个方法(清理函数),要么就是undefined,其他情况都会报错。

# useImperativeHandle

推荐使用一个自定义的 innerRef 来代替原生的 ref,否则要用到 forwardRef 会搞的类型很复杂。

type ListProps = {
  innerRef?: React.Ref<{ scrollToTop(): void }>
}

function List(props: ListProps) {
  useImperativeHandle(props.innerRef, () => ({
    scrollToTop() { }
  }))
  return null
}
1
2
3
4
5
6
7
8
9
10

# 自定义 Hook

如果你想仿照 useState 的形式,返回一个数组给用户使用,一定要记得在适当的时候使用 as const,标记这个返回值是个常量,告诉 TS 数组里的值不会删除,改变顺序等等…… 否则,你的每一项都会被推断成是「所有类型可能性的联合类型」,这会影响用户使用。

export function useLoading() {
    const [isLoading, setState] = React.useState(false);
    const load = (aPromise: Promise<any>) => {
        setState(true);
        return aPromise.finally(() => setState(false));
    };
    // ✅ 加了 as const 会推断出 [boolean, typeof load]
    // ❌ 否则会是 (boolean | typeof load)[]
    return [isLoading, load] as const;
}
1
2
3
4
5
6
7
8
9
10

或者定义返回类型

export interface Actions {
  setTrue: () => void;
  setFalse: () => void;
  toggle: (value?: boolean | undefined) => void;
}

export default function useBoolean(defaultValue = false): [boolean, Actions] {
  const [state, { toggle }] = useToggle(defaultValue);

  const actions: Actions = useMemo(() => {
    const setTrue = () => toggle(true);
    const setFalse = () => toggle(false);
    return { toggle, setTrue, setFalse };
  }, [toggle]);

  return [state, actions];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17