1. 初始化state方法
class Video extends React.Component {
state = {
name: "Mike",
age: 12,
obj: {a: "a", b: 1},
array: ["abc", "bcd"],
}
_changeData = ()=>{
this.setState({
name: "Nike",
age: 13
})
}
}
2. 定义组件时设置类型验证
class Video extends React.Component {
static defaultProps = {
autoPlay: false,
maxLoops: 10,
};
static propTypes = {
autoPlay: React.PropTypes.bool,
maxLoops: React.PropTypes.number.isRequired,
posterFrameSrc: React.PropTypes.string.isRequired,
videoSrc: React.PropTypes.string.isRequired,
};
}
3. props 验证所以类型表
React.createClass({
propTypes: {
optionalArray: React.PropTypes.array,
optionalBool: React.PropTypes.bool,
optionalFunc: React.PropTypes.func,
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
optionalNode: React.PropTypes.node,
optionalElement: React.PropTypes.element,
optionalMessage: React.PropTypes.instanceOf(Message),
optionalEnum: React.PropTypes.oneOf(['News', 'Photos']),
optionalUnion: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
React.PropTypes.instanceOf(Message)
]),
optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),
optionalObjectWithShape: React.PropTypes.shape({
color: React.PropTypes.string,
fontSize: React.PropTypes.number
}),
requiredFunc: React.PropTypes.func.isRequired,
requiredAny: React.PropTypes.any.isRequired,
customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) {
return new Error('Validation failed!');
}
}
},
});