我遇到了新的React,Webpack项目的问题。无法在浏览器控制台出现时解决错误:“未捕获的TypeError:(0,_react.createClass)不是函数”
你能帮助我吗?
Opera控制台屏幕截图
webpack.config.babel.js
import path from 'path';
export default {
mode: 'development', // development, production or none
entry: './assets/js/index.js',
output: {
path: path.resolve(__dirname, 'dist/js'),
filename: 'bundle.js',
sourceMapFilename: 'bundle.map'
},
// devtool: '#source-map',
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel-loader']
}]
}
};
.babelrc
{
"presets": [
"env",
"stage-0",
"react"
]
}
index.js
import { createClass } from 'react';
import { render } from 'react-dom';
const Note = createClass({
displayName: 'Note',
render() {
return (
<div className='TEST'>
Hello world
</div>
);
}
});
render(
<Note />,
document.body
);
视觉工作室代码中的项目截图
的package.json
{
"dependencies": {
"normalize.css": "^8.0.0",
"react": "^16.4.0",
"react-dom": "^16.4.0"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"eslint": "^4.19.1",
"eslint-plugin-react": "^7.8.2",
"path": "^0.12.7",
"webpack": "^4.10.2",
"webpack-cli": "^2.1.4"
},
"name": "notes",
"version": "0.0.1",
"description": "",
"main": "webpack.config.babel.js",
"scripts": {
"build": "webpack",
"watch": "webpack --watch",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Andrew Dyachenko",
"license": "ISC"
}
答案 0 :(得分:2)
createClass
功能已从react v16.0
移除。
我不知道你为什么要这样。 (也许如果你需要迁移一个旧项目)
无论如何,您需要安装一个不同的包create-react-class
。
npm i -s create-react-class
然后
import { render } from 'react-dom';
import createReactClass from 'create-react-class';
const Note = createReactClass({
displayName: 'Note',
render() {
return (
<div className='TEST'>
Hello world
</div>
);
}
});
render(
<Note />,
document.getElementById('root') // rendering on document.body is bad. You should avoid it. Create a tag with id `root`
);
如果您正在关注任何旧教程(如果有的话),则新语法为
import { render } from 'react-dom';
import { component }from 'react';
class Note extends component{
displayName: 'Note',
render() {
return (
<div className='TEST'>
Hello world
</div>
);
}
}
// or, just simply (in this case)
const Note2 = () => <div className='TEST'>Hello world</div>;
render(
<Note />,
document.getElementById('root')
);