【问题标题】:React conditional rendered Form auto submitsReact 条件渲染表单自动提交
【发布时间】:2018-04-21 01:17:01
【问题描述】:

在开发个人项目时,我遇到了一个我以前从未遇到过的通知。

在最高的组件中有一个三元,每个都包含一个简单的形式:

{ this.state.isConnected
      ? <Chat handleSubmit={ this.handleChatSubmit } />
      : <Register handleSubmit={ this.handleRegisterSubmit } />
}

当状态改变 (isConnected) 时,它会显示聊天。聊天包含一个表单,以便用户可以使用按钮和键来提交他们的消息。但是,当我使用表单元素时,它会给出下一个通知: Screenshot 1: Chrome debugger notice.

注册.js

<form onSubmit={ () => this.props.handleSubmit(this.state) }>
      <label>
        <span>Username *</span>
        <input
          type="text"
          name="username"
          onChange={ this.handleChange }
        />
      </label>

      <button>Sign in</button>
    </form>

聊天.js

<form onSubmit={ () => this.props.handleSubmit(this.state) }>
      <label>
        <input
          type="text"
          onChange={ this.handleChange }
        />
      </label>

      <button>Send message</button>
    </form>

每个表单都被阻止提交如下:

handleSubmit = ({ message }) => {
...
this.socket.send(JSON.stringify(data))

event.preventDefault()

}

此问题正在使页面重新加载并将消息添加到查询参数中:http://localhost:8080/?chat=it+is+refreshing

如果我使用不同的方法并停止使用表单元素,它会起作用。

【问题讨论】:

    标签: javascript forms reactjs


    【解决方案1】:

    提交表单时,必须使用e.preventDefault(),否则提交表单时会导致页面重新加载。

    onSubmit={ () =&gt; this.props.handleSubmit(this.state) } 更改为onSubmit={ (e) =&gt; e.preventDefault();this.props.handleSubmit(this.state) }

    或者添加一个你的表单的 onSubmit 函数调用的函数,如下所示:

    handleSubmitForm = e => {
      e.preventDefault();
      this.props.handleSubmit(this.state)
    } 
    

    【讨论】:

    • 您好,MEnf,感谢您的评论。我在回调句柄提交中使用 event.PreventDefault()。我会更新问题。
    • 嗨,男士们,您是对的。我知道不提供任何参数应该可以让您访问事件本身,就像在reactjs.org/docs/forms.html 上建议的那样。我现在看到当你提供一个参数时它是一个代理?
    • 我可能应该让我的代码更清晰一点,参数中的e 代表元素的事件处理程序。您需要从函数参数访问它以将代理绑定到正在调用它的元素。 reactjs.org/docs/handling-events.html
    猜你喜欢
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 2017-04-15
    • 2021-05-16
    • 1970-01-01
    相关资源
    最近更新 更多