React propType无法读取undefined的属性

时间:2017-10-14 19:20:39

标签: reactjs

使用propTypes验证道具会产生以下错误:

  

TypeError:无法读取未定义的属性“string”。

     

TypeError:无法读取未定义的属性'func'。

相关代码位于代码段的底部:

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
}

2 个答案:

答案 0 :(得分:19)

您需要安装prop-types包,然后添加import语句

import PropTypes from prop-types;

在班上。

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

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

答案 1 :(得分:0)

正如palsrealm所述,您需要添加prop-types包,然后在Proptypes之前删除React。以下应该起作用:

Projects.propTypes = {
   projects: PropTypes.string,
   onDelete: PropTypes.func
}