0

我正在创建简单的东西,以寻求将按钮单击事件捕获到某些文本或获得一些警报。ReactJS JSX 代码粘贴在下面:

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>
    );
},

});

SearchBar我在 MVC cshtml 中使用上述组件作为:

@Html.React("SearchBar", new{ })

按钮在 html 页面上呈现,但无法更改this.state.message单击事件的值。我在哪里做错了?

4

2 回答 2

2

这个问题有两点需要关心

  1. 在 cshtml 或 Views\Shared_Layout.cshtml 文件中添加所有jsx文件 uwins 脚本标记或使用包。例如@System.Web.Optimization.Scripts.Render("~/bundles/main")

  2. 之后调用@Html.ReactInitJavaScript()方法。

现在 Click 事件肯定会起作用。

于 2016-08-18T12:49:48.563 回答
0

也许你渴望这样:

render: function() { return <div> <button onClick={this.test1}>Change Message</button> {this.state.message} </div> }

this改为使用self

于 2016-08-17T13:51:51.010 回答