ES 6データ検証
2895 ワード
ES 6 classデータチェック
import React, { PropTypes } from 'react';
const propTypes = {
// JavaScript
optionalArray: PropTypes.array,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
// : , ,DOM 。
optionalNode: React.PropTypes.node,
// ReactElement
optionalElement: PropTypes.element,
//
optionalMessage: PropTypes.instanceOf(Message),
//
optionalEmun: PropTypes.oneOf(['News', 'Photos']),
//
optionalUnion: PropTypes.oneOfType([
PropTypes.array,
PropTypes.string,
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
}),
// `isRequired` prop 。
requiredFunc: React.PropTypes.func.isRequired,
//
requiredAny: React.PropTypes.any.isRequired,
// 。 Error 。
// `console.warn` , `oneOfType` 。
customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) {
return new Error('Validation failed!');
}
}
// isRequired, ,
requiredFunc: PropTypes.func.isRequired
};
class Profile extends React.Component {
render() {
return (
{/* this.pros */}
my name is { this.props.name }
my age is { this.props.age }
);
}
}
Profile.propTypes = propTypes;
export default Profile;
propTypesをクラスに書きます.import React, { PropTypes } from 'react';
export default class Profile extends React.Component {
static get propTypes() {
return {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired
};
}
constructor(props) {
super(props);
this.state = { count: 0 };
this.likeMe = this.likeMe.bind(this);
}
componentDidMount() {
// 1 , count 1
setTimeout(() => {
this.likeMe();
}, 1000);
}
likeMe() {
let count = this.state.count;
count += 1;
console.log(count);
this.setState({ count });
}
render() {
return (
{/* this.pros */}
my name is { this.props.name }
my age is { this.props.age }
Like Me Count: { this.state.count }
);
}
}