谁能给出一个用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);
}
// ...
}
发布于 2016-04-02 20:33:38
您可以通过以下方式定义默认道具:
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 = { /* ... */ };
// ...
}
发布于 2019-01-08 10:41:44
假设你有一个Movie无状态组件,那么你可以像下面这样定义proptype:
const Movie = props => {
return (
<div>
<h3>{props.movie.title}</h3>
</div>
);
};
Movie.propTypes = {
movie: PropTypes.shape({
title: PropTypes.string.isRequired
})
};
Movie. defaultProps = {
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>
);
}
}
发布于 2020-04-16 11:33:58
我使用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;
https://stackoverflow.com/questions/36378200
复制