有人能举一个在TypeScript中的React组件类上定义defaultProps的例子吗?

interface IProps {}
interface IState {}

class SomeComponent extends Component<IProps, IState> {
    // ... defaultProps ?
    // public defaultProps: IProps = {}; // This statement produces an error

    constructor(props: IProps) {
        super(props);
    }

    // ...
}

推荐答案

您可以通过以下方式定义默认props :

export class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: props.initialCount};
    this.tick = this.tick.bind(this);
  }
  tick() {
    this.setState({count: this.state.count + 1});
  }
  render() {
    return (
      <div onClick={this.tick}>
        Clicks: {this.state.count}
      </div>
    );
  }
}
Counter.propTypes = { initialCount: React.PropTypes.number };
Counter.defaultProps = { initialCount: 0 };

在TypeScript中,这相当于将defaultProps定义为类主体内的静态字段:

class SomeComponent extends Component<IProps, IStates> {
    public static defaultProps: IProps = { /* ... */ }; 
    // ...
}

Typescript相关问答推荐

类型是工作.但它失go 了正确变体的亮点..为什么?或者如何增强?

有没有办法适当缩小类型?

对于使用另一个对象键和值类型的对象使用TS Generics

如何创建泛型类型组件来使用React Native的FlatList或SectionList?'

Redux—Toolkit查询仅在不为空的情况下添加参数

类型{}上不存在属性&STORE&A;-MobX&A;REACT&A;TYPE脚本

我可以为情态车使用棱角形的路由守卫吗?

在函数中打字推断记录的关键字

React Typescript项目问题有Redux-Toolkit userSlice角色问题

有没有办法传递泛型类型数组,以便推断每个元素的泛型类型?

有没有一种更好的方法来存储内存中的数据,而不是在类型脚本中使用数组和基于索引的函数?

有没有更干净的方法来更新**key of T**的值?

有没有一种方法可以提升对象的泛型级别,而对象的值是泛型函数?

窄SomeType与SomeType[]

有没有一种方法可以防止我的组件包在其中安装样式组件'; node 模块中的s目录

在Vite中将SVG导入为ReactComponent-不明确的间接导出:ReactComponent

Typescript 和 Rust 中跨平台的位移数字不一致

带动态键的 TS 功能

通过函数将对象文字类型映射到另一种类型的方法或解决方法

如何为对象创建类型,其中键是只读且动态的,但值是固定类型?