简体   繁体   English

React.createClass不是函数,可能是webpack编译错误

[英]React.createClass is not a function, may be webpack compling error

I used webpack to set react envirement, and run the code using this line: 我使用webpack设置反应环境,并使用以下代码运行代码:

webpack -d && webpack-dev-server --content-base src/ --inline --hot --port 1234

The cmd runs some builds, and than shows the line: 该cmd运行一些构建,然后显示以下行:

webpack: Compiled successfully.

instead of : 代替 :

webpack: bundle is now VALID

like I saw in the example. 就像我在示例中看到的那样。

and than it says on the browser console: 并在浏览器控制台上显示:

Uncaught TypeError: React.createClass is not a function

What could it be? 会是什么呢?

my dependencies: 我的依赖:

"dependencies": {
    "react": "^16.0.0",
    "react-dom": "^16.0.0"
 },
 "devDependencies": {
   "babel-core": "^6.26.0",
   "babel-loader": "^7.1.2",
   "babel-preset-es2015": "^6.24.1",
   "babel-preset-react": "^6.24.1",
   "webpack": "^3.8.1",
   "webpack-dev-server": "^2.9.4"
 }

my code: 我的代码:

var React = require('react');
var ReactDOM = require('react-dom');

// Create component
var TodoComponent = React.createClass({
  render: function () {
    return(
      <h1>Hello!!</h1>
    );
  }
});

// put component into html page

ReactDOM.render(<TodoComponent />, document.getElementById('todo-container'));

By the way, this is my first question here, so please forgive me for starters mistakes.. ;) 顺便说一句,这是我在这里的第一个问题,所以请原谅我的入门错误。

In version 16.x of React, React.createClass has been moved to its own package named create-react-class . 在React的React.createClass版本中, React.createClass已移至其自己的名为create-react-class的包中。

Documentation here: https://reactjs.org/blog/2017/09/26/react-v16.0.html#packaging 此处的文档: https : //reactjs.org/blog/2017/09/26/react-v16.0.html#packaging

So, you should do npm i create-react-class --save . 因此,您应该执行npm i create-react-class --save

And then adjust your code: 然后调整您的代码:

var React = require('react');
var ReactDOM = require('react-dom');
var createClass = require('create-react-class');

// Create component
var TodoComponent = createClass({
  render: function () {
    return(
      <h1>Hello!!</h1>
    );
  }
});

// put component into html page

ReactDOM.render(<TodoComponent />, document.getElementById('todo-container'));

Otherwise, you should use the ES6 class Component, which is more idiomatic in react: 否则,您应该使用ES6 class Component,它在React中更加惯用:

var React = require('react');
var ReactDOM = require('react-dom');

// Create component
class TodoComponent extends React.Component {
    render() {
        return(
            <h1>Hello!!</h1>
        );
    }
}

// put component into html page

ReactDOM.render(<TodoComponent />, document.getElementById('todo-container'));

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

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