PropTypes给我一个字符串类型的错误

问题描述 投票:0回答:1

更新节点模块后,我在正在运行的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"
    ]
  }
}

文件到use prop-types.

reactjs react-proptypes
1个回答
0
投票

您以错误的方式定义了原型。原型在组件定义之外定义:

// This is wrong
function App(props) 
    {
        let name: PropTypes.string

设置原型的正确方法:

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

function App(props)
{
  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;
© www.soinside.com 2019 - 2024. All rights reserved.