【组件开发笔记】类型检查-类组件
声明props和导出props都和函数组件一样,命名方式也是【组件名+Props】规范。
定义默认的props时,可以直接用static defaultProps ,就不需要用?这个可选操作符修饰(是否必传)
声明state:
/**
* 组件状态, 不需要暴露
*/
interface State {
......
}
示例:
import React from 'react';
export interface ComponentProps {
......
}
interface State {
......
}
/**
* 继承React.Component
*/
export class Component extends React.Component<ComponentProps, State> {
/**
* 默认参数
*/
public static defaultProps = {
defaultTitle: 'hello world',
};
/**
* 初始化State
*/
public state = {
title: this.props.defaultTitle,
};
/**
* 生命周期
*/
public componentDidMount() {}
public componentWillUnmount() {}
public componentDidCatch() {}
public componentDidUpdate(prevProps: ComponentProps, prevState: State) {}
/**
* 渲染
*/
public render() {
return (
<div onClick={this.handleTitle}>{this.state.title}</div>
);
}
/**
* 组件私有方法
*/
private handleTitle = () => {
this.setState(({ title}) => ({ title: title + '嘎嘎嘎' }));
};
}
声明子组件:
【静态属性形式声明】
export class Component extends React.Component<ComponentProps> {
public static Header = Header;
public static Footer = Footer;
public render() {
return <div className="xxxx">{this.props.children}</div>;
}
}
泛型:
export class Component<T> extends React.Component<ComponentProps<T>> {
public render() {}
}
还有高阶组件
因为我看不懂 而且据大牛说用类组件写高阶组件有一些痛点,所以我不学这个了(#^.^#)

浙公网安备 33010602011771号