[英]onSubmit event handler not working in Reactjs form
I am new to react and have this form:我是新来的反应并有这种形式:
class CustomForm extends React.Component {
handleFormSubmit = (e) => {
e.preventDefault();
const title = e.target.elements.title.value;
const content = e.target.elements.content.value;
console.log(title, content)
}
render() {
return (
<div>
<Form onSubmit={ this.handleFormSubmit }>
<FormItem label='Title'>
<Input name='title' placeholder='Put a title here' />
</FormItem>
<FormItem label='Content'>
<Input name='content' placeholder='Enter some content' />
</FormItem>
<FormItem>
<Button type='primary' htmlType='submit'>Submit</Button>
</FormItem>
</Form>
</div>
)
}
}
The form is not submitting anything/nothing in console log.该表单未在控制台日志中提交任何内容/没有任何内容。 I tried it with onSubmitCapture
and that seems to work.我用onSubmitCapture
试过了,这似乎有效。 How do I fix this?我该如何解决?
From your code it looks like you are using some custom component <Form>
.. this is not the normal <form>
because custom <Form>
component might not have the prop onSubmit
.从您的代码看来,您正在使用一些自定义组件<Form>
.. 这不是正常的<form>
因为自定义<Form>
组件可能没有道具onSubmit
。 Go through the documentation of the component you are using. Go 通过您正在使用的组件的文档。
button with type='submit'
will trigger the form onSubmit
Handler type='submit'
按钮将触发表单onSubmit
Handler
You need to bind the event handlers in the constructor in order to work.您需要在构造函数中绑定事件处理程序才能工作。 Read more here https://reactjs.org/docs/handling-events.html :在这里阅读更多https://reactjs.org/docs/handling-events.html :
class CustomForm extends React.Component {
constructor(props) {
super(props)
this.handleFormSubmit = this.handleFormSubmit.bind(this)
}
handleFormSubmit = (e) => {
e.preventDefault();
const title = e.target.elements.title.value;
const content = e.target.elements.content.value;
console.log(title, content)
}
render() {
return (
<div>
<Form onSubmit={ this.handleFormSubmit }>
<FormItem label='Title'>
<Input name='title' placeholder='Put a title here' />
</FormItem>
<FormItem label='Content'>
<Input name='content' placeholder='Enter some content' />
</FormItem>
<FormItem>
<Button type='primary' htmlType='submit'>Submit</Button>
</FormItem>
</Form>
</div>
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.