我是ReactJS的初学者,我正在尝试运行以下代码:
@{
ViewBag.Title = "Index";
}
<h2>Hello World-React JS</h2>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script type="text/javascript">
var HelloWorldComponent = React.createClass({
getInitialState: function () {
return {
serverMessage: ''
};
},
componentDidMount: function () {
$.get('/Home/getmessage', function (result) {
if (this.isMounted) {
this.setState({
serverMessage: result
});
}
}.bind(this));
},
render: function () {
return ("<h1>{this.state.serverMessage}</h1>");
}
});
ReactDOM.render(<HelloWorldComponent />, document.getElementById("helloworldcontainer"));
</script>
<div id="helloworldcontainer"></div>
正如您所看到的,这是VS2017 MVC简单测试应用程序。
实际上,在VS编辑器中,我有一些投诉显示在屏幕截图下方:
如何解决并运行它?
答案 0 :(得分:0)
将您的脚本类型更改为<script type="text/babel">
示例代码:
<html>
<head>
<title>demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
</head>
<body>
<div id="container"/></div>
<script type="text/babel">
class MessageBox extends React.Component {
constructor(props){
super(props);
}
render() {
return (
<div>
<div className={`messageBox ${this.props.type} || hidden`}>
{this.props.message}
</div>
</div>
);
}
}
class NameInput extends React.Component {
constructor(props) {
super(props);
this.state = {
message: {
type: "success",
body: "Now my message is in NameInput's state"
}
}
this.buttonClicked = this.buttonClicked.bind(this);
}
buttonClicked(evt) {
alert("hi");
}
render() {
let msg = this.state.message;
return (
<div>
<label>Name: <input type="text" /></label>
<button onClick={this.buttonClicked}>Click me!</button>
<MessageBox type={msg.type} message={msg.body}/>
</div>
)
}
}
ReactDOM.render(
<NameInput />,
document.getElementById('container')
);
</script>
</body>
</html>
希望这有帮助。
正如@Adeel Imran建议的那样,仅仅检查反应是如何起作用的,这很好。对于将来的开发,请使用babel-cli并尝试在单独的文件中编写组件。