任何人都可以在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); } // ... }
您可以通过以下方式定义默认道具:
原文链接:https://www.f2er.com/react/301331.htmlexport 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 = { /* ... */ }; // ... }