父组件 father_属性校验.js页面
import React, { Component } from "react";
import ChildCpn from "./child_子组件";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
nameArr: ["张三", "李四", "王五"],
};
}
render() {
const {nameArr} = this.state
return (
<div>
<h1>我是父组件</h1>
<hr />
<ChildCpn nameData={nameArr} names={11111}/>
</div>
);
}
}
子组件 child_子组件.js页面
import React, { Component } from "react";
// 1.验证传给子组件的一个包
import PropType from "prop-types";
class ChildCpn extends Component {
render() {
const { nameData,names} = this.props;
return (
<div>
<h1>我是子组件</h1>
<ul>
{nameData.map((item, index) => {
return <li key={index}>{item}</li>;
})}
</ul>
<hr/>
<h2>{names}</h2>
</div>
);
}
}
// 2.
ChildCpn.propTypes = {
// 3.
nameData:PropType.array,
names:PropType.string
}
export default ChildCpn;
实际截图

image.png
当没有给子组件传递任何值的话,可以设置默认值

image.png
网友评论