更新节点模块后,在运行的React 16应用程序中使用prop-types库时出现错误。
我创建了一个新的React 16 create-react-app项目来检查此问题,并以相同的方式发生错误。
我的代码:
index.js文件:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<App name="Test prop-types"/>,
document.getElementById('root')
);
App.js文件:
import React from 'react';
import PropTypes from 'prop-types';
function App(props)
{
let name: PropTypes.string;
name = (props.name)
? props.name
: "Xxx";
return (
<div className="App">
<header className="App-header">
<p>Learn React - {name}</p>
</header>
</div>
);
}
export default App;
错误:
Line 8:23: Parsing error: Unexpected reserved type string
6 | function App(props)
7 | {
> 8 | let name: PropTypes.string
我的 package.json 内容:
{
"name": "test-prop-types",
"version": "0.1.0",
"private": true,
"dependencies": {
"prop-types": "^15.7.2",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-scripts": "3.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
答案 0 :(得分:2)
您以错误的方式定义了原型。原型在组件定义之外定义:
// This is wrong
function App(props)
{
let name: PropTypes.string
设置原型的正确方法:
import React from 'react';
import PropTypes from 'prop-types';
function App(props)
{
let name = (props.name)
? props.name
: "Xxx";
return (
<div className="App">
<header className="App-header">
<p>Learn React - {name}</p>
</header>
</div>
);
}
// Setting the proptypes of the `App` component
App.propTypes = {
name: PropTypes.string
};
export default App;