问题
I am creating simple stuff seeking for capturing button click event to some text or get some alert. ReactJS JSX code is pasted below:
var SearchBar = React.createClass({
getInitialState: function() {
return {message: "test"};
},
test1: function(e) {
alert('hi');
this.setState({message: "New Message"});
},
render: function() {
var self = this;
return (
<div>
<button onClick={self.test1}>Change Message</button>
{this.state.message}
</div>
);
},
});
I use above SearchBar
component in MVC cshtml as:
@Html.React("SearchBar", new{ })
Button get rendered on html page, but unable to change this.state.message
value on click event. Where am I doing mistake?
回答1:
Maybe you desire so:
render: function() {
return <div>
<button onClick={this.test1}>Change Message</button>
{this.state.message}
</div>
}
Use this
instead self
回答2:
There are two things that need to care about this issue
Add all
jsx
file uwins Script tag or using bundle in cshtml or in Views\Shared_Layout.cshtml file. e.g. @System.Web.Optimization.Scripts.Render("~/bundles/main")Call
@Html.ReactInitJavaScript()
method after that.
Now Click event surely get work.
来源:https://stackoverflow.com/questions/38996394/mvc-reactjs-button-onclick-event-not-get-fired