reactjs – React propType无法读取undefined的属性

前端之家收集整理的这篇文章主要介绍了reactjs – React propType无法读取undefined的属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用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语句

从prop-types导入PropTypes;

在你的班级顶部.

The PropTypes have been moved from React to their own package prop-types.

编辑:如评论中所述,这仅适用于React版本15.5及更高版本.

猜你在找的React相关文章