我有一个非常标准的表格:
export default class Form extends React.Component {
constructor (props) {
super(props)
this.state = {
email: '',
refCode: ''
}
this.onSubmit = this.onSubmit.bind(this)
this.changeEmail = this.changeEmail.bind(this)
}
changeEmail (event) {
this.setState({ email: event.target.value })
}
onSubmit () {
this.props.onSubmit(this.state)
}
render () {
return (
<div>
<h2>{this.props.title}</h2>
<form className={cx('Form')} onSubmit={this.onSubmit}>
<input
className={cx('Form-email')}
onChange={this.changeEmail}
value={this.state.email}
type='email'
placeholder='email' />
<input className={cx('Form-refcode')} type='text' placeholder='enter referal code' />
<input className={cx('Form-btn')} type='submit' value='sign up' />
</form>
</div>
)
}
}
然后我想通过这个函数在父组件中处理表单提交
submitForm (value) {
event.preventDefault()
console.log(value.email)
}
/* ... */
<Form
title='What are you waiting for?! Sign up now'
onSubmit={this.submitForm} />
我遇到的问题是 event.preventDefault()
不工作,我似乎也没有通过控制台记录正确的值。
我假设我没有在此处正确传递或接收值,但我不知道哪里出错了。
最佳答案
在子组件中将事件
(你可以随意命名)参数传递给父组件的方法
onSubmit (event) {
this.props.onSubmit(event, this.state)
}
在父组件中这样做
submitForm (event, value) {
event.preventDefault()
console.log(value.email)
}
关于javascript - 如何将表单事件传递给父组件以防止默认?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37540678/