MVC-ReactJS button onclick event not get fired

不羁岁月 提交于 2019-12-12 04:59:09

问题


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

  1. 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")

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!