为什么我们应该从'react'中使用import React [英] why should we use import React from 'react'

查看:71
本文介绍了为什么我们应该从'react'中使用import React的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在案例ii 的App.js模块中学习React js,因为 render()方法用于将JSX转换为dom元素,所以我必须导入React在Person.js中,我们正在创建一个箭头函数,然后将其导出,以便可以将其导入并在App模块中使用渲染函数,无论我们在App模块中导入React的方式如何,它都将在person模块中转换JSX并在DOM上呈现,但是当我们在Person.js中删除以下代码时引发错误时

i am learning React js in case ii App.js module i have to import React because the render() method is used to convert JSX to dom elements how ever in Person.js we are creating a arrow function and we are exporting it so that it can be imported and used in the App modules render function how ever in App module we have React imported and it will convert the JSX in module person and gets rendered on DOM but when it throws an error when we remove the below code in Person.js

import React from 'react' in Person.js

它引发错误

React'必须在使用JSX的范围内.

有人可以解释

i)为什么我们需要在Person.js中导入react?

i)why do we need to import react in Person.js?

ii)为什么删除上面的代码时会引发错误?

ii)why was it throwing error when we remove the above code?

情况i)

Person.js

Person.js

 import React from 'react'

 const person = () => {
 return <p>This is person module used inside app module</p>
 };

 export default person

案例ii)

App.js

App.js

import React, { Component } from 'react';
import './App.css'
import Person from './Person/Person'

class App extends Component {
render() {
return (
  <div className="App">
    <h1>this is app module and i am being used as the root component</h1>
     <Person/>
  </div>
);}}

export default App;

推荐答案

如果您将一些JSX提供给Babel,则您会看到JSX只是 React.createElement 调用的糖.这就是为什么如果我们使用JSX,则需要导入React.

If you give some JSX to Babel, you will see that JSX is just sugar for React.createElement calls. This is why we need to import React if we use JSX.

输入

<p>This is person module used inside app module</p>

输出

/*#__PURE__*/
React.createElement("p", null, "This is person module used inside app module");

这篇关于为什么我们应该从'react'中使用import React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆