【发布时间】:2020-09-29 14:36:06
【问题描述】:
我的页面上有一个表单,其中包含我想要调用的 onSubmit 函数,但它似乎没有被触发,因为 console.log 从未出现。
import React, { Component } from 'react'
class EmailSignUp extends Component {
constructor(props) {
super(props)
this.state = {
email: '',
lastName: '',
error: false
}
this.handleChange = this.handleChange.bind(this)
this.onSubmitForm = this.onSubmitForm.bind(this)
}
onSubmitForm (e) {
console.log('function has run');
e.preventDefault()
let formData = new FormData(e)
const { formAction } = this.props
const requestOptions = {
method: 'POST',
body: formData
}
fetch(formAction, requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error))
}
handleChange (e) {
const value = e.target.value
const inputId = e.target.id
this.setState(() => ({
[inputId]: value
}))
}
render () {
const { error } = this.state
return (
<div id='email-form' className='container'>
<form
name='form'
id='form'
onSubmit={this.onSubmitForm}
method='post'
>
<div className='form-group'>
<label htmlFor='email'>Email</label>
<input
type='email'
name='Email'
className='form-control'
id='email'
placeholder='youremail@email.com'
onChange={this.handleChange}
value={this.state.email}
required
/>
</div>
<div className='form-group'>
<label htmlFor='lastName'>Last name</label>
<input
type='text'
name='lastName'
className='text form-control'
id='lastName'
placeholder='Last Name'
onChange={this.handleChange}
value={this.state.lastName}
required
/>
</div>
<button
type='submit'
name='Submit'
value='Subscribe'
className='btn btn-primary item_cta'
readOnly
/>
</form>
{error && <p>{error}</p>}
</div>
)
}
}
export default EmailSignUp
【问题讨论】:
-
从表单中删除
method,为什么按钮上有readOnly? -
如果我删除该方法,那么它仍然无法运行,它会以所有表单数据作为查询进入 URL?比如 www.test.com?email=&lastname=
-
您查看过控制台错误吗?很明显,他们是如何尝试使用 FormData
Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.: stackblitz.com/edit/react-et2my9?file=src/Form.js 的问题
标签: javascript reactjs forms post