我需要在我的视图中呈现React组件(html文件)。我正在使用webpack 1并收到component undefined
的错误。我试图使用window.component,但它也没有用。如果我在我的组件中使用RenderDOM,一切都很好。
我的组件:
export class SmallCart extends BaseComponent {
...
render() {...}
}
Webpack 1 config:
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var BowerWebpackPlugin = require('bower-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: {
...
myComponent: "./wwwroot/js/es6/SmallCart/SmallCart.jsx",
...
},
output: {
path: __dirname + "/dist",
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
module: {
loaders: [
{
test: /\.(png|jpg|gif|ico)$/,
loader: "file-loader?name=assets/[name]-[hash:6].[ext]"
}, {
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "url-loader?limit=10000&minetype=application/font-woff&name=assets/[name]-[hash:6" +
"].[ext]"
}, {
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "file-loader?name=assets/[name]-[hash:6].[ext]"
}, {
test: /\.scss$/i,
loader: ExtractTextPlugin.extract(['css-loader?-autoprefixer!postcss-loader', 'sass'])
}, {
test: /\.css$/i,
loader: ExtractTextPlugin.extract(['css-loader?-autoprefixer!postcss-loader'])
}, {
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
},
progress: true,
resolve: {
modulesDirectories: ['node_modules'],
extensions: ['', '.json', '.js']
},
externals: {
jquery: "jQuery",
react: "React",
reactDOM: "ReactDOM"
},
plugins: [
new webpack.ProvidePlugin({'window.Nette': 'nette-forms', 'window.jQuery': 'jquery', jQuery: 'jquery', $: 'jquery'}),
new webpack
.optimize
.CommonsChunkPlugin({
filename: "commons.js", name: "commons",
}),
new ExtractTextPlugin("frontend.css"),
]
}
在我看来,我有这个:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react.js" charset="utf-8"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react-dom.min.js" charset="utf-8"></script>
<script type="text/javascript" src="/dist/commons.js" charset="utf-8"></script>
<script type="text/javascript" src="/dist/SmallCart.js" charset="utf-8"></script>
<script type="text/javascript">
window.data_for_react = {};
ReactDOM.render(React.createElement(SmallCart, { dataSource : data_for_react}, document.getElementById('box-to-rendering')));
</script>
但是在render方法中,组件未定义。 怎么了?可以在视图中渲染组件吗?
感谢您的时间。
修改
好的,现在我尝试使用window.SmallBasket和webpack config更新到:
...
new webpack
.optimize
.CommonsChunkPlugin({
names: [
"commons"
],
minChunks: Infinity
}),
...
它有效。但是如果没有窗口属性,我仍然无法解决它。
答案 0 :(得分:1)
尝试将您视图中的所有反应代码放在以下内容中:
document.addEventListener('DOMContentLoaded', () => {
//... your ReactDOM.render stuff here
};
您需要等待DOM元素加载才能获得getElementById。