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)
| 归档时间: |
|
| 查看次数: |
48095 次 |
| 最近记录: |