在react的一个评论组件中,大致如下的写法:

render() {
    return (
        <form>
            <div>
                <label htmlFor="username">用户名: </label>
                <input
                  type="text"
                  name="username"
                  value={ this.state.username }
                  onChange={ this.handleOnChange.bind(this, 'username') }
                  required
                ></input>
            </div>
            <div>
                <label htmlFor="commentContent">评论内容: </label>
                <textarea
                  ref={ textarea => this.textArea = textarea }
                  value={this.state.commentContent}
                  onChange={ this.handleOnChange.bind(this, 'commentContent') }
                  name="commentContent"
                  cols="30"
                  rows="10"
                ></textarea>
            </div>
            <button onClick={ this.submitComment.bind(this) }>发布</button>
        </form>
    );
  }

其中的form表单里面使用了原生button元素,神奇的是,每次发表评论后,页面会重新加载,这就很可怕了。在大佬的帮助下,debug的过程略过,结论就是:

在form表单中的button如果没有显示写明type属性为什么,则默认是为type="submit"

来MDN走一波:

button的类型。可选值:
submit: 此按钮将表单数据提交给服务器。如果未指定属性,或者属性动态更改为空值或无效值,则此值为默认值。

不过提交到服务器,这个就一定会导致刷新页面吗?

其实主要是我们没有在form里面写action的时候,提交是直接提交到本页的,也就是网址后面,这样会造成页面的刷新:

也就是MDN描述

The action attribute defines where the data gets sent. Its value must be a valid relative or absolute URL. If this attribute isn't provided, the data will be sent to the URL of the page containing the form; the current page.

还有最关键的一句:

The server then responds, generally handling the data and loading the URL defined by the action attribute, causing a new page load or a refresh of the existing page if the action points to itself or is ommited
// 例如我们没有写action,会导致键值对添加到url中去
http://localhost:3000/?username=sc&commentContent=

不过这里有一个误区:看着上面的描述会觉得是因为提交的数据到了URL上导致URL改变了,所以会刷新,这个是错误的啊!

第一,按照上述思路的话,如果我每次提交相同的内容就不会刷新,实际上是会刷新的

第二,可以打开network,记录一下点击发布时,提交的请求和响应,就可以看到,这是因为server端是直接返回了一个新的html的document才导致的浏览器重新渲染(刷新),作为测试,可以设置action="https://www.baidu.com",这样提交的时候就会发现,点击提交后,会跳到百度页面呐!

以上也说明了MDN解释的严谨性

那为什么平时我们使用form+button的组合却感觉没有遇到过呢?

那么来看一下ElementUI-button组件的源码

其中的props:

nativeType: {
    type: String,
    default: 'button'
}

哦豁,豁然开朗

标签: none

添加新评论