2017-06-13 67 views
-1

我試圖用React創建一個新的應用程序。propTypes中的反應錯誤

我創建了一個新的應用程序的指示上進行如下陣營網頁:

npm install -g create-react-app

create-react-app my-app

cd my-app

npm start

安裝的陣營版本是15.5.4。

然後,虛擬類是在 'Dummy.js' 文件所作的研究:

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"/>

它運作良好,但是當我改變,因爲在注意語法陣營博客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

任何人的幫助我找出原因?

+0

只是搬出他的proptypes聲明外組件。 –

回答

1

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.PropTypes已被棄用獨立的prop-types包,截至React v15.5:

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

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

謝謝!它完美的作品! –