简体   繁体   English

create-react-app 和 TypeScript 错误:使用 JSX 时“React”必须在范围内

[英]create-react-app and TypeScript error: 'React' must be in scope when using JSX

I initialised a React project with TypeScript using the CLI command create-react-app client --typescript .我使用 CLI 命令create-react-app client --typescript用 TypeScript 初始化了一个 React 项目。 Then, I ran npm start but received the following compilation error:然后,我运行npm start但收到以下编译错误:

./src/App.js
  Line 26:13:  'React' must be in scope when using JSX  react/react-in-jsx-scope

I did not even modify the boilerplate project provided by create-react-app other than removing unnecessary logo files, and my previous React apps done using TypeScript compiled just fine.除了删除不必要的徽标文件之外,我什至没有修改create-react-app提供的样板项目,而且我之前使用 TypeScript 完成的 React 应用程序编译得很好。 Below is my App.tsx and index.tsx file: (note that the logo in App.tsx was removed, and I did not touch index.tsx )下面是我的App.tsxindex.tsx文件:(注意,在标志App.tsx被删除,我没有碰index.tsx

index.tsx:索引.tsx:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: 
serviceWorker.unregister();

App.tsx:应用程序.tsx:

import React from 'react';
import './App.css';

function App() {
  return (
    <div className="App">
        Lorem
    </div>
  );
}

export default App;

React and ReactDOM are imported, so what caused this error? ReactReactDOM是导入的,那么是什么导致这个错误呢?

Edit:编辑:

I found out that npm start , which runs react-scripts start , is compiling my .tsx files into .js files, which probably caused this issue.我发现运行react-scripts start npm start正在将我的.tsx文件编译成.js文件,这可能导致了这个问题。 What might have caused the above behaviour?什么可能导致上述行为?

try尝试


const RootApp:React.FC = () => {
  return (
     <React.StrictMode>
    <App />
  </React.StrictMode>
  );
}

render(<RootApp />, document.getElementById("root"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM