React 学习(三) 属性验证PropTypes
propTypes & defaultProps
import React, { Component } from "react";
import Proptypes from "prop-types";
// Function
function ChildCpn(props) {
const { name, age, height } = props;
const { names } = props;
return (
<div>
<h2>SubComponent:{name + " " + age + " " + height}</h2>
<div>
{names.map((item, index) => {
return <li key={index}>{item}</li>;
})}
</div>
</div>
);
}
// Class
class ChildCpn2 extends Component {
static propTypes = {};
static defaultProps = {};
render() {
const { name, age, height, names } = this.props;
return (
<div>
<h2>SubCompnent2:{name + " " + age + " " + height}</h2>
<div>
{names.map((item, index) => {
return <li key={index}>{item}</li>;
})}
</div>
</div>
);
}
}
// Custom Validation Rule
ChildCpn.propTypes = {
name: Proptypes.string.isRequired,
age: Proptypes.number,
height: Proptypes.number,
names: Proptypes.array,
};
ChildCpn2.propTypes = {
name: Proptypes.string,
age: Proptypes.number,
height: Proptypes.number,
names: Proptypes.array,
};
// defaultValue
ChildCpn.defaultProps = {
name: "HelloKitty",
age: 30,
height: 1.78,
names: ["defalut"],
};
ChildCpn2.defaultProps = {
name: "BlackAngel",
age: 30,
height: 1.78,
names: ["defalut"],
};
export default class App extends Component {
render() {
return (
<div>
<ChildCpn
name="Smallstars"
age={18}
height={1.83}
names={["abc", "de"]}
/>
<ChildCpn />
<ChildCpn2 age={18} height={1.83} names={["abc", "de"]} />
</div>
);
}
}
每天进步一点点