javascript - 在 propTypes 中 react 错误

标签 javascript facebook reactjs syntax-error

我正在尝试使用 React 创建一个新应用。

我按照 React 网页上的说明创建了一个新应用程序,如下所示:

npm install -g create-react-app

create-react-app my-app

cd my-app

npm start

安装的 React 版本是 15.5.4。

然后,在'Dummy.js'文件中创建一个Dummy类用于学习:

import React from 'react';

class Dummy extends React.Component {
   render() {
      return <div>{this.props.name}</div>
   }
   propTypes : {
      name: React.PropTypes.string.isRequired
   }
}

在 App.js 文件中,我添加了一行 <Dummy name="this is dummy class"/> .

它运行良好,但是当我按照 React 博客 link 中的说明更改语法时,

import React from 'react';
import PropTypes from 'prop-types';

class Dummy extends React.Component {
   render() {
      return <div>{this.props.name}</div>
   }
   Component.propTypes = {
      name: React.PropTypes.string.isRequired
   };
}

然后,它返回语法错误(意外标记):

enter image description here

谁能帮我看看是什么原因?

最佳答案

参见 React propTypes docs对于声明 propTypes 的预期方式:

class Dummy extends React.Component {}

Dummy.propTypes = {
  name: React.PropTypes.string.isRequired
}

create-react-appBabel config supports using the following syntax sugar这相当于同一件事:

class Dummy extends React.Component {
  static propTypes = {
    name: React.PropTypes.string.isRequired
  }
}

此外,根据文档,从 React v15.5 开始,React.PropTypes 已弃用,取而代之的是单独的 prop-types 包:

import PropTypes from 'prop-types'
import React from 'react'

class Dummy extends React.Component {
  static propTypes = {
    name: PropTypes.string.isRequired
  }
}

关于javascript - 在 propTypes 中 react 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44511400/

相关文章:

javascript - ng 类不工作。我哪里做错了?

javascript - 错误类型错误 : Cannot set property 'paginator' of undefined

javascript - 为什么要与typeof的返回值进行严格比较

javascript - React Routing,刷新不渲染特定 View ,而是重定向到父 View

javascript - 如何使用 match 从字符串中返回字符?

javascript - Facebook Graph API - 如何请求额外的权限

javascript - Facebook Event.subscribe comments.create 不工作

facebook - 使用图谱 API 获取(识别)对评论的回复

css - React 元素中无法识别 minmax CSS 函数

javascript - 如何使用反引号将 react 元素插入数组