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

时间:2017-11-08 15:42:00

标签: javascript reactjs

我使用webpack设置react envirement,并使用以下代码运行代码:

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

cmd运行一些构建,然后显示行:

webpack: Compiled successfully.

而不是:

webpack: bundle is now VALID
就像我在例子中看到的那样。

并且在浏览器控制台上显示:

Uncaught TypeError: React.createClass is not a function

它可能是什么?

我的依赖项:

"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"
 }

我的代码:

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'));

顺便说一下,这是我的第一个问题, 所以请原谅我的首发错误..;)

1 个答案:

答案 0 :(得分:2)

在React版本16.x中,React.createClass已移至名为create-react-class的自己的包中。

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

所以,你应该做npm i create-react-class --save

然后调整您的代码:

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'));

否则,你应该使用ES6 class组件,这个组件更具惯用性:

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'));