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

新手上路,请多包涵

谁能展示一个在 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);
    }

    // ...
}

原文由 oei 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 718
2 个回答

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

 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 = { /* ... */ };
    // ...
}

原文由 shadeglare 发布,翻译遵循 CC BY-SA 3.0 许可协议

我使用 if 语句来检查 prop 的值是否未定义,如果是,我设置一个默认值,否则我使用传递过来的值。

 interface Props {
  style: any;
  bounces?: boolean | undefined;
  extraHeight?: number | undefined;
}

const DynamicView: React.FC<Props> = (props) => {
  return (
    <KeyboardAwareScrollView
      style={props.style}
      bounces={
        (props.bounces = props.bounces === undefined ? false : props.bounces)
      }
      extraHeight={
        (props.extraHeight =
          props.extraHeight === undefined ? 15 : props.extraHeight)
      }>
      {props.children}
    </KeyboardAwareScrollView>
  );
};

export default DynamicView;

原文由 NickM 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进