gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:23:03 25 4
gpt4 key购买 nike

更新节点模块后,我在运行的 React 16 应用程序中使用 prop-types 库时遇到了错误。

我创建了一个新的React 16 create-react-app项目来检查这个问题,并且错误以同样的方式发生。


我的代码:

index.js file:

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 file:

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.

最佳答案

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

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

设置 proptypes 的正确方法:

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;

关于javascript - PropTypes 给我一个字符串类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59750290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com