使用propTypes验证props会出现以下错误:
TypeError: Cannot read property ‘string’ of undefined.
TypeError: Cannot read property ‘func’ of undefined.
import React from 'react'; import ProjectItem from './ProjectItem'; class Projects extends React.Component { deleteProject(title) { this.props.onDelete(title); } render() { let projectItems; if (this.props.project) { projectItems = this.props.project.map(project => { return ( <ProjectItem key={project.title} project={project} onDelete={this.deleteProject.bind(this)} /> ) }); } return ( <div className="Projects"> {projectItems} </div> ); } } Projects.propTypes = { projects: React.PropTypes.string,onDelete: React.PropTypes.func }
您需要安装prop-types包,然后添加import语句
原文链接:https://www.f2er.com/react/300798.html从prop-types导入PropTypes;
在你的班级顶部.
The PropTypes have been moved from React to their own package prop-types
.
编辑:如评论中所述,这仅适用于React版本15.5及更高版本.