我的表单上的React生成按钮会不断刷新页面

Gen*_*ias 17 html javascript jquery node.js reactjs

我试图使用node.js和react.js创建一个聊天应用程序,但我无法解决这个问题,每次我点击我的页面按钮时它都会刷新页面.我是网站开发的新手,所以如果我的问题非常明显,请原谅我.我的代码可以在下面找到:

// Array of messages to be rendered
messageArray = [];
var socket = io();
// Prompt the user for their username
var user = prompt("Please enter your name", "Anonymous");
// Emit username information so that it can be kept track of
socket.emit('new user', user);


$('#chat').submit(function() {
    // When the user hits submit, create a message object with 
    // information about their name, time sent, message, and socket id.
    // The socket id will be filled on the server side
    alert("hey");
    var date = new Date();
    var message = user + " (" + date.toLocaleTimeString('en-US') + "): " + $('#m').val();
    var messageJSON = {text:message, username:user, id:"", time:date}
    socket.emit('chat message', messageJSON);
    // Reset the value field
    $('#m').val('');
    return false;
});

// On receiving a chat message, update messageArray and 
// rerender the ViewingBox
socket.on('chat message', function(messages){
    messageArray = [];
    for (var i = 0; i < messages.length; i++) {
        alert(messages[i].text)
        messageArray.push(messages[i].text);
    }

    React.render(
        <ViewingBox />,
        document.getElementById('root')
    );
});

// ViewingBox holds the view of the page and is updated whenever
// a new message is received
var ViewingBox = React.createClass({
    render: function() {
        return (
            <div>
                <h2>Global Chat: Logged in as {user}</h2>

                <ul id="messages">
                    {messageArray.map(function(data, i) {
                        return (<li>{data}</li>)
                    })} 
                </ul>
                <form id="chat" action="#">
                    <input id="m" autoComplete = "off" />
                     /*
                     *
                     Button in question
                     *
                     */
                    <button>Send</button>
                </form>
            </div>
        );
    }
});


// Render the viewingBox when the page initially loads
React.render(
    <ViewingBox />,
    document.getElementById('root')
);
Run Code Online (Sandbox Code Playgroud)

这是相关的HTML:

<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <div id="root"></div>
    <script src="https://fb.me/react-0.13.3.js"></script>
    <script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
    <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>  
    <script type="text/jsx" src="/reactclient.js"></script> 
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

由于某种原因,我的提交功能中的警报永远不会到达.只要我按下按钮,它就会刷新页面.我不确定这是否是React,jQuery的问题,还是我错过了HTML的一些奇怪的事情.我已经尝试在我的按钮中使用'onsubmit ="return false"'并且还使用preventDefault(),但仍然无法查明问题.如何修复页面的行为,以及我可以考虑使用哪些工具来更密切地分析此问题?

Fel*_*ing 40

这是默认的HTML行为.默认情况下,按钮是提交按钮,因此单击它们将提交表单.如果你不想那样,那就把它变成一个"哑"按钮:

<button type="button">Send</button>
Run Code Online (Sandbox Code Playgroud)

你也可以简单地删除<form>元素,因为你似乎没有对它做任何事情.


另一个问题是,正如另一个答案中所解释的那样,您试图在按钮存在之前绑定事件处理程序.

混合jQuery和React的方式很混乱,使你的代码更难维护,更难以推理.只需将所有内容保存在React组件中:

var ViewingBox = React.createClass({
    getInitialState: function() {
        return {
            message: ''
        };
    },

    _onMessageChange: function(event) {
        this.setState({message: event.target.value});
    },

    _send: function() {
        var date = new Date();
        var message = user + " (" + date.toLocaleTimeString('en-US') + "): " + this.state.message;
        var messageJSON = {text:message, username:user, id:"", time:date}
        socket.emit('chat message', messageJSON);
        // Reset the value field
        this.setState({message: ''});
    },

    render: function() {
        return (
            <div>
                <h2>Global Chat: Logged in as {user}</h2>

                <ul id="messages">
                    {messageArray.map(function(data, i) {
                        return (<li>{data}</li>)
                    })} 
                </ul>
                <form id="chat" action="#">
                    <input
                        value={this.state.message}
                        onChange={this._onMessageChange}
                        autoComplete="off"
                    />
                    <button type="button" onClick={this._send}>Send</button>
                </form>
            </div>
        );
    }
});
Run Code Online (Sandbox Code Playgroud)

同样,messageData应该是组件状态的一部分,但我将转换留给您.

基本上你目前使用React的方式并没有给你带来太多好处.我建议阅读更多React文档,特别是ReactInteractivity中的Thinking 和动态UI.


Ada*_*dam 12

对我来说就像一个委托问题 - 我打赌#chat当你创建提交处理程序时,我不会在DOM中.

尝试将提交委托给文档(并阻止默认操作):

$(document).on('submit','#chat',function(e) {
 e.preventDefault();
 ...
});
Run Code Online (Sandbox Code Playgroud)

  • @GenericAlias:请记住,虽然这可能提供短期解决方案,但您真的应该重构代码以正确使用React. (4认同)