[英]Uncaught ReferenceError: React is not defined
Hi I know this type of question has been asked quite a few times but I couldn't get the answer.嗨,我知道此类问题已被问过很多次,但我无法得到答案。
I am trying to write a React hello world example.我正在尝试编写一个 React hello world 示例。 I have only two files one app.jsx and another homepage.jsx.
我只有两个文件,一个是 app.jsx,另一个是 homepage.jsx。 I am using webpack to bundle the files.
我正在使用 webpack 来捆绑文件。
But when I run the code I get Uncaught ReferenceError: React is not defined
但是当我运行代码时,我得到
Uncaught ReferenceError: React is not defined
My homepage.jsx looks like this我的 homepage.jsx 看起来像这样
"use strict";
var React = require('react');
var Home = React.createClass({
render : function() {
return (
<div className="jumbotron">
<h1> Hello World</h1>
</div>
);
}
});
module.exports = Home;
My app.js looks like this我的 app.js 看起来像这样
var ReactDOM = require('react-dom');
var Home = require('./components/homePage');
ReactDOM.render(
<Home/>,
document.getElementById('app')
);
In browser it throws Uncaught ReferenceError: React is not defined
at line 7 ie where I am requiring homepage.在浏览器中,它抛出
Uncaught ReferenceError: React is not defined
at line 7 ,即我需要主页的地方。
But when I add var React = require('react') in app.jsx it works fine.但是当我在 app.jsx 中添加 var React = require('react') 时它工作正常。
I don't understand this.我不明白这个。 I have included react in homepage.jsx where I am making use of it.
我在 homepage.jsx 中包含了 react ,我正在使用它。 In app.jsx I only require react-dom becuase I don't use React.
在 app.jsx 中,我只需要 react-dom 因为我不使用 React。 Then why it is giving error in app.jsx.
那么为什么它在 app.jsx 中给出错误。
Pls help!!请帮忙!!
Change your app.js
to this将您的
app.js
更改为此
var React = require('react');
var ReactDOM = require('react-dom');
var Home = require('./components/homePage');
ReactDOM.render(
<Home/>,
document.getElementById('app')
);
JSX is transformed into React.createElement()
calls, thus React is required in scope. JSX 转化为
React.createElement()
调用,因此作用域内需要 React。 So yes, you are using React
in app.js
.所以是的,您正在
app.js
中使用React
。 Get used to import it whenever you use JSX or direct React.*
calls.习惯于在使用 JSX 或直接调用
React.*
时导入它。
You can have it without require it in your code.您可以在代码中不使用它的情况下使用它。
Add to webpack.config.js :添加到webpack.config.js :
plugins: [
new webpack.ProvidePlugin({
"React": "react",
}),
],
See https://webpack.js.org/plugins/provide-plugin/#root见https://webpack.js.org/plugins/provide-plugin/#root
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.