js,事件按钮未写入



此处的Form.js代码

import React , {Component} from 'react';
import { Form, Input, Button  } from 'antd';
import axios from 'axios';

class CustomForm extends Component {

handFormSubmit2 = (event) => {
event.preventDefault()
const name = event.target.elements.name.value;
const comment = event.target.elements.comment.value;
console.log(name , comment)    

}
render(){
return (
<>
<Form onSubmit={this.handFormSubmit2}>
<Form.Item label="Name">
<Input name='name' placeholder="Enter name here" />
</Form.Item>
<Form.Item label="Comment">
<Input name="comment" placeholder="Comment here" />
</Form.Item>
<Form.Item>

<Button type="primary" htmlType="submit">Submit</Button>
</Form.Item>
</Form>
</>
);
}
}
export default CustomForm;

我面临的问题是,即使我删除了事件,按钮也不起作用。preventDefault((它仍然没有提交和刷新页面

您正在使用antd阅读表单文档,您应该使用他们的onFinish回调,而不是onSubmit

<Form onFinish={this.handFormSubmit2}>
<Form.Item label="Name">
<Input name='name' placeholder="Enter name here" />
</Form.Item>
<Form.Item label="Comment">
<Input name="comment" placeholder="Comment here" />
</Form.Item>
<Form.Item>

<Button type="primary" htmlType="submit">Submit</Button>
</Form.Item>
</Form>

这是您使用antd 的完整示例

import React , {Component} from 'react';
import { Form, Input, Button  } from 'antd';
import axios from 'axios';

class CustomForm extends Component {

handFormSubmit2 = (values) => {
console.log(values.name , values.comment)    

}
render(){
return (
<>
<Form onFinish={this.handFormSubmit2}>
<Form.Item label="Name" name='name'>
<Input  placeholder="Enter name here" />
</Form.Item>
<Form.Item label="Comment" name="comment">
<Input  placeholder="Comment here" />
</Form.Item>
<Form.Item>

<Button type="primary" htmlType="submit">Submit</Button>
</Form.Item>
</Form>
</>
);
}
}
export default CustomForm;

工作示例

最新更新