如何使用TypeScript在React组件类上声明defaultProps?

oei*_*ei 27 typescript reactjs

任何人都可以展示defaultProps在TypeScript 中定义React组件类的示例吗?

interface IProps {}
interface IState {}

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

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

    // ...
}
Run Code Online (Sandbox Code Playgroud)

sha*_*are 53

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

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 };
Run Code Online (Sandbox Code Playgroud)

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

class SomeComponent extends Component<IProps, IStates> {
    public static defaultProps: IProps = { /* ... */ }; 
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 提供的链接不再讨论`defaultProps`.相反,请参阅https://facebook.github.io/react/docs/react-component.html#defaultprops (7认同)
  • 为了使用TypeScript,您应该通过在分号之前附加'as IProps'将对象强制转换为IProps. (2认同)