【发布时间】:2018-12-25 14:08:15
【问题描述】:
我在 case ii App.js 模块中学习 React js 我必须导入 React 因为 render() 方法用于将 JSX 转换为 dom 元素在 Person.js 中,我们创建了一个箭头函数,我们正在导出它,以便可以在 App 模块渲染函数中导入和使用它,但是在 App 模块中我们导入了 React,它将转换模块 person 中的 JSX 并在 DOM 上呈现,但是当我们在 Person.js 中删除以下代码时它会引发错误
import React from 'react' in Person.js
报错
使用 JSX 时,React' 必须在作用域内如果我们在 React 类提供的方法(如 render )中声明 JSX,它应该会报错。
谁能解释一下
i)为什么我们需要在 Person.js 中导入 react?
ii)为什么删除上面的代码会报错?
案例一)
Person.js
import React from 'react'
const person = () => {
return <p>This is person module used inside app module</p>
};
export default person
案例二)
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 在 Person.js 中使用的吗
-
静态分析允许 Babel 检测 JSX(通过一些插件)。然后它使用更多插件来实际分解它并将 JSX 解析/转换为
React.createElement。 -
感谢此评论有助于了解编译器如何理解 JSX
标签: javascript reactjs react-router react-redux