简体   繁体   English

使用 JSX 时,必须在 scope 中获取“反应”

[英]Getting 'React' must be in scope when using JSX

I am new to react and I tried the following code我是新手,我尝试了以下代码

person.js人.js

const element = <h1>Hello world</h1>;
export default element;

App.js应用程序.js

import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import Person from '../src/person/person';



function Hello() {
  return Person.element;
}



class App extends Component {

  render() {

    return (
      <div className="App">
        <Hello></Hello>
      </div>
    );
  }
}

export default App;

But getting the below errors但得到以下错误

work/my-app/src/person/person.js 3:17 error 'React' must be in scope when using JSX react/react-in-jsx-scope使用 JSX react/react-in-jsx-scope 时,work/my-app/src/person/person.js 3:17 错误“React”必须在 scope 中

When I changed to a simple hello word as below, then it works fine.当我更改为如下所示的简单问候词时,它可以正常工作。

person.js人.js

const element = 'hello world';
export default element;

I tried with different ways by checking different forum我通过检查不同的论坛尝试了不同的方式

  1. importing the ReactDom导入 ReactDom
  2. in person.js changed to module.exports=element在 person.js 中更改为 module.exports=element

The use of HTML within JS code is known as JSX.在 JS 代码中使用 HTML 称为 JSX。 The <h1>...</h1> is JSX. <h1>...</h1>是 JSX。 You need to import React before you use JSX.你需要在使用 JSX 之前导入React Simply shift the import statements before any use of JSX.只需在使用 JSX 之前转换 import 语句。

person.js人.js

import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import Person from '../src/person/person';

const element = <h1>Hello world</h1>;
export default element;

You need to import React in every file that exports a component (App in this case).您需要在每个导出组件的文件(在本例中为 App)中导入 React。

The latest React 17 Version: No need to include React in the scope最新的 React 17 版本:scope 中无需包含 React

If you are struggling with ESlint or run-time CRA warnings, follow these temporary steps to fix until CRA v4 is released: https://github.com/facebook/create-react-app/issues/9850如果您遇到 ESlint 或运行时 CRA 警告,请按照以下临时步骤进行修复,直到 CRA v4 发布: https://github.com/facebook/create-react-app/issues/9850

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

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