Uncaught ReferenceError: React is not defined

醉酒当歌 提交于 2019-12-21 03:18:33

问题


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. I have only two files one app.jsx and another homepage.jsx. I am using webpack to bundle the files.

But when I run the code I get Uncaught ReferenceError: React is not defined

My homepage.jsx looks like this

"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

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 i.e where I am requiring homepage.

But when I add var React = require('react') in app.jsx it works fine.

I don't understand this. I have included react in homepage.jsx where I am making use of it. In app.jsx I only require react-dom becuase I don't use React. Then why it is giving error in app.jsx.

Pls help!!


回答1:


Change your app.js to this

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. So yes, you are using React in app.js. Get used to import it whenever you use JSX or direct React.* calls.




回答2:


You can have it without require it in your code.

Add to webpack.config.js:

plugins: [
  new webpack.ProvidePlugin({
    "React": "react",
  }),
],

See https://webpack.js.org/plugins/provide-plugin/#root



来源:https://stackoverflow.com/questions/35341994/uncaught-referenceerror-react-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!