无法提交表单 react-bootstrap

29

我有以下的 react-bootstrap 组件:

        <FormGroup onSubmit={this.gotEmail} role="form">
          <FormControl type="text" className="form-control"/>
          <Button className="btn btn-primary btn-large centerButton" type="submit">Send</Button>
        </FormGroup>

当我点击“发送”按钮时,我希望表单被提交。

但是,如果我点击按钮,控制权不会到达this.gotEmail方法。

为什么会这样呢?

4个回答

36

FormGroup 不提供 on submit 事件。你可以用 form 元素将其包裹,并在其中附加事件处理器:


<form onSubmit={this.gotEmail}>
  <FormGroup role="form">
    <FormControl type="text" className="form-control"/>
    <Button className="btn btn-primary btn-large centerButton" type="submit">Send</Button>
  </FormGroup>
</form>

只是好奇,role="form"有什么用?例如,我只是得到了<FormGroup>,它可以工作。 - Ycon
所以,如果我像文档中所说使用<Form horizontal>(https://react-bootstrap.github.io/components.html#forms-horizontal),由于没有onSubmit属性,我是否需要用另一个表单进行包装并在DOM中拥有2个表单? - migueloop
1
从版本0.30.2开始,您可以直接使用<Form horizontal onSubmit={this.gotEmail}>@migueloop - Kevin Lee

20

我觉得有一件事情还缺少。

gotEmail 中,应该加上 preventDefault,这样如果用户按下“回车”键,页面就不会重新加载:

gotEmail(event){ 
  event.preventDefault();
  // code you want to do
}

12

从0.30.2版本开始,您可以将其包装在<Form>中,该标签支持onSubmit属性:

<Form onSubmit={this.gotEmail}>
  <FormGroup role="form">
  <FormControl type="text" className="form-control"/>
  <Button className="btn btn-primary btn-large centerButton" 
  type="submit">Send</Button>
  </FormGroup>
</Form>

3

我使用以下代码片段成功地使用了reactstrap:

<Button onClick={this.onSubmit}>Login</Button> 


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接