有人可以在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);
}
// ...
}
答案 0 :(得分:51)
您可以通过以下方式定义默认道具:
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 = { /* ... */ };
// ...
}
答案 1 :(得分:0)
如果您有一个电影无状态组件,那么可以定义如下的原型:
const Movie = props => {
return (
<div>
<h3>{props.movie.title}</h3>
</div>
);
};
Movie.propTypes = {
movie: PropTypes.shape({
title: PropTypes.string.isRequired
})
};
Movie.defaultProp = {
movie: PropTypes.shape({})
};
对于类组件,您可以执行以下操作,也可以使用与上述相同的模式:
export default class Movie extends React.Component {
static propTypes = {
movie: PropTypes.shape({
title: PropTypes.string.isRequired
}),
desc: PropTypes.string
};
static defaultProps = {
desc: 'No movie is available'
};
render() {
return (
<div>
<h3>{this.props.movie.title}</h3>
<h3>{this.props.movie.desc}</h3>
</div>
);
}
}
答案 2 :(得分: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;