我有一个 FormBox.js 组件
import PropTypes from 'prop-types';
const FormBox = (props) => {
return <form className={`shadow p-3 ${props.className}`}>{props.children}</form>;
};
FormBox.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
};
export default FormBox;
在 App.js 我有一个表单提交,但 event.preventDefault() 不起作用。我了解这是因为此表单是我的组件。如何防止表单提交?
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
post: {
title: '',
body: '',
},
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
async handleSubmit(event) {
event.preventDefault();
const response = await postApi.addPost(this.state.post);
console.log(response);
}
render() {
return (
<div className="container">
<FormBox onSubmit={this.handleSubmit} className="mt-4">
<Button className="btn-info" type="submit" />
</FormBox>
</div>
);
}
}
export default App;
1 个回答