在React中,可以添加對(duì)props類(lèi)型的檢察。如:
import PropTypes from 'prop-types';
class Greeting extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
Greeting.propTypes = {
name: PropTypes.string
};
覺(jué)見(jiàn)的ProtoTypes:
import PropTypes from 'prop-types';
MyComponent.propTypes = {
// You can declare that a prop is a specific JS primitive. By default, these
// are all optional.
optionalArray: PropTypes.array,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol,
// Anything that can be rendered: numbers, strings, elements or an array
// (or fragment) containing these types.
optionalNode: PropTypes.node,
// A React element.
optionalElement: PropTypes.element,
// You can also declare that a prop is an instance of a class. This uses
// JS's instanceof operator.
optionalMessage: PropTypes.instanceOf(Message),
// You can ensure that your prop is limited to specific values by treating
// it as an enum.
optionalEnum: PropTypes.oneOf(['News', 'Photos']),
// An object that could be one of many types
optionalUnion: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.instanceOf(Message)
]),
React中還可以通過(guò)defaultTypes來(lái)設(shè)置默認(rèn)參數(shù):
class Greeting extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
// Specifies the default values for props:
Greeting.defaultProps = {
name: 'Stranger'
}; // 設(shè)置默認(rèn)props值
因?yàn)楹瘮?shù)式組件不支持state、ref,一般不建議使用函數(shù)式組件。
想學(xué)計(jì)算機(jī)技術(shù)嗎?需要1對(duì)1專(zhuān)業(yè)級(jí)導(dǎo)師指導(dǎo)嗎?想要團(tuán)隊(duì)陪你一起進(jìn)步嗎?歡迎加我為好友!微信號(hào):iTekka。