我的表單上的React生成按鈕會不斷刷新頁面

[英]React generated button on my form keeps refreshing the page


I was trying to make a chat application using node.js and react.js, but I cannot get past this issue where every time I click my page's button it refreshes the page. I'm fairly new to web development so forgive me if my issue is extremely obvious. My code can be found below:

我試圖使用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')
);

Here is the relevant HTML:

這是相關的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>

For some reason the alert in my submit function is never reached. It just refreshes the page whenever I hit the button. I'm not sure whether this is an issue with React, jQuery, or just some odd thing that I missed with my HTML. I already tried using 'onsubmit = "return false"' in my button and preventDefault() as well but was still unable to pinpoint the problem. How do I fix my page's behavior, and what tools might I consider using to analyze this issue more closely?

由於某種原因,我的提交功能中的警報永遠不會到達。只要我按下按鈕,它就會刷新頁面。我不確定這是否是React,jQuery的問題,或者只是我錯過了HTML的一些奇怪的事情。我已經嘗試在我的按鈕中使用'onsubmit =“return false”'並且還使用preventDefault(),但仍然無法查明問題。如何修復頁面的行為,以及我可以考慮使用哪些工具來更密切地分析此問題?

3 个解决方案

#1


10  

Sounds to me like a delegation issue - I'll bet #chat isn't in the DOM when you are creating the submit handler.

對我來說就像一個委托問題 - 我敢打賭,當你創建提交處理程序時,#chat不在DOM中。

Try delegating the submit to the document (and preventing the default action):

嘗試將提交委托給文檔(並阻止默認操作):

$(document).on('submit','#chat',function(e) {
 e.preventDefault();
 ...
});

#2


31  

This is default HTML behavior. Buttons are submit buttons by default, so clicking them will submit the form. If you don't want that, then make it a "dumb" button:

這是默認的HTML行為。默認情況下,按鈕是提交按鈕,因此單擊它們將提交表單。如果你不想那樣,那就把它變成一個“啞”按鈕:

<button type="button">Send</button>

You could also simply remove the <form> element since you don't seem to do anything with it.

您也可以簡單地刪除

元素,因為您似乎沒有對它執行任何操作。


The other issue is, as explained in the other answer, that you are trying to bind the event handler before the button exists.

另一個問題是,正如另一個答案中所解釋的那樣,您試圖在按鈕存在之前綁定事件處理程序。

The way you mix jQuery and React is messy, makes your code harder to maintain and harder to reason about. Just keep everything inside the React component:

混合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>
        );
    }
});

Similarly, messageData should be part of the state of the component, but I leave the conversion up to you.

同樣,messageData應該是組件狀態的一部分,但我將轉換保留給您。

Basically the way you use React currently doesn't give you much benefit. I recommend to read more of the React documentation, especially Thinking in React and Interactivity and Dynamic UIs.

基本上你目前使用React的方式並沒有給你帶來太多好處。我建議閱讀更多React文檔,特別是React和Interactivity中的Thinking和動態UI。

#3


1  

Your problem is something to do with controlled and uncontrolled components in React. In uncontrolled component: If you are not calling a handler function to handle the submit OR If you do not turn off the default behavior of the HTML,then Submit button would alwaysbe handled by the DOM.

您的問題與React中的受控和非受控組件有關。在不受控制的組件中:如果您沒有調用處理程序函數來處理提交OR,如果您沒有關閉HTML的默認行為,那么提交按鈕將始終由DOM處理。

In controlled component: A handler function would take care of the action upon submit. Example for controlled component:

在受控組件中:處理程序函數將在提交時處理操作。受控組件的示例:

handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    **event.preventDefault();**
  }

<form onSubmit={**this.handleSubmit**}>
    <label>
      Name:
      <input type="text" value={this.state.value} onChange={this.handleChange} />
    </label>
    <input type="submit" value="Submit" />
  </form>

Detailed discussion is here: https://facebook.github.io/react/docs/uncontrolled-components.html https://facebook.github.io/react/docs/forms.html

詳細討論如下:https://facebook.github.io/react/docs/uncontrolled-components.html https://facebook.github.io/react/docs/forms.html


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/06/25/7208d92d7feb9b06f8f819da06ce99e7.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com