我是ReactJS的新手。我在head标签中将此库称为:

    <script src="react/build/react.js"></script>
<script src="react/build/react-dom.js"></script>
<script src="https://unpkg.com/[email protected]/browser.min.js"></script>

<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/15.8.23/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

<script src="chat-component.js" type="text/babel"></script>


这是我的反应代码:

var ChatApp = React.createClass({
  getInitialState: function () {
    return {
        messages: [],
        socket: window.io('http://localhost:3000')
    }
},
componentDidMount: function () {
  var self = this;
    this.state.socket.on("receive-message", function (msg) {
        console.log(msg);
        self.setState({messages: self.state.messages.push(msg)})
    });
},
render: function () {

    return (

        <div>
            <input id="message" type="text"/>
            <button type="button"  onClick={this.submitMessage} id="demo" value="send">send</button>
        </div>
    )
},
submitMessage: function () {

    var message = $('#message').value;
    // this.socket.emit("new-message", message);
     console.log(message);
},

});

ReactDOM.render(
<ChatApp />,
document.getElementById("chat")
);


为什么Button onClick在我的代码中不起作用?同样在检查器中,onClick不存在:

<button type="button" id="demo" value="send">send</button>


我知道我的问题是重复的,但我真的找不到解决方案。

最佳答案

submitMessage函数放在render上方。

执行render时,应定义this.submitMessage。在您的代码中,仅在render之后定义它。因此,它不会被调用。并使用val()使用jQuery从文本框中获取值



var ChatApp = React.createClass({
  getInitialState: function () {
    return {
        messages: [],
    }
  },
  submitMessage: function () {

    var message = $('#message').val();
    // this.socket.emit("new-message", message);
     console.log(message);
  },
  render: function () {

      return (

          <div>
              <input id="message" type="text"/>
              <button type="button"  onClick={this.submitMessage} id="demo" value="send">send</button>
          </div>
      )
  }
});

ReactDOM.render(
<ChatApp />,
document.getElementById("chat")
);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="chat"></div>

关于javascript - 按钮onClick在reactjs中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40201980/

10-12 13:40