[英]Render Transpiled ES6 in CSHTML
I have 我有
Tutorial.jsx Tutorial.jsx
class ShoppingList extends React.Component {
render() {
return (<div>Milk</div>);
}
}
export default ShoppingList;
webpack.config.js webpack.config.js
module.exports = {
...
output: './React/bundle.js',
...,
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
presets: ['es2015', 'react'],
}
}
]
}
}
In my CMD prompt, when I run webpack -w
everything is green and I see my bundle.js file appearing where it should, in the React folder. 在我的CMD提示符下,当我运行webpack -w
所有内容均为绿色,并且在React文件夹中看到我的bundle.js文件出现在应有的位置。 Opening it, I see 打开它,我看到了
...
var ShoppingList = function (_React$Component) {
...
}
...
so it looks like that's all good. 所以看起来一切都很好。
Now I want to render ShoppingList in my _Layout.cshtml file. 现在,我想在_Layout.cshtml文件中呈现ShoppingList。
Question: How do I do this? 问题:我该怎么做? I've tried all methods below and get React errors all the time about invalid parameter type, or passing in the wrong element, or whatever. 我已经尝试了下面的所有方法,并且始终因无效的参数类型或传入错误的元素等而得到React错误。 My CSHTML is below. 我的CSHTML在下面。
<div id="content1">render here</div>
....
<script src="~/React/bundle.js"></script>
<script>
ReactDOM.render("ShoppingList", document.getElementById("content1"));
ReactDOM.render(ShoppingList, document.getElementById("content1"));
ReactDOM.render(<ShoppingList />, document.getElementById("content1"));
</script>
Can someone please let me know if 有人可以让我知道是否
The best results I've got so far is to see ShoppingList in my DOM explorer but no HTML was actually rendered. 到目前为止,我得到的最好结果是在DOM资源管理器中看到ShoppingList,但实际上没有呈现HTML。 It came out <shoppinglist ...></shoppinglist>
which appears wrong to me. 出来了<shoppinglist ...></shoppinglist>
,这对我来说似乎是错误的。
Thanks. 谢谢。
You should have this inside your entry file: 您应该在输入文件中包含以下内容:
import ShoppingList from 'path-to/ShoppingList';
ReactDOM.render(<ShoppingList />, document.getElementById("content1"));
In the CSHTML page the additional script tag is not required. 在CSHTML页面中,不需要其他脚本标签。
Your original example does not work because: 您的原始示例无效,因为:
<ShoppingList />
) needs to be transpiled before it can be used in HTML page. 必须先转换JSX语法( <ShoppingList />
),然后才能在HTML页面中使用。 If you really need to use a component within a CSHTML page, you can make the component global: 如果确实需要在CSHTML页面中使用组件,则可以使该组件成为全局组件:
window.ShoppingList = ShoppingList
inside the file that defines the component. 在定义组件的文件中。
And use vanilla javascript instead of JSX syntax: 并使用香草javascript而不是JSX语法:
ReactDOM.render(React.createElement(ShoppingList), document.getElementById("content1"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.