我正在尝试创建一个具有要提交的表单的网站。但是,即使我现在也有一个http://formspree.io/可以转发给我,并且在有以下情况时也可以转发给我:
<form action="http://formspree.io/myaddress@gmail.com" method="post">
<label for="Name">Name</label><br/>
<input type="text" name="Name"/><br/>
<label for="emailAddress">E-Mail address</label><br/>
<input type="text" name="emailAddress"/><br/>
<textarea id="subject" name="subject" placeholder="Write something.."></textarea><br/>
<input type="submit" name="SUBMIT"/>
</form>
我决定让React组件创建一个有状态的模型来提交表单。但是,当我按下“提交”按钮时,它什么也没做,而且我也不知道如何获取它来更改页面上的内容。我的代码是:
handleFormSubmit(e) {
e.preventDefault();
let userData = this.state.newUser;
fetch('http://formspree.io/myAddress@gmail.com', {
method: "POST",
body: JSON.stringify(userData),
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
}).then(response => {
response.json().then(data => {
console.log("Successful" + data);
});
});
}
我的导入和构造函数是:
import Input from "./FormComponents/Input";
import TextArea from "./FormComponents/TextArea";
import Select from "./FormComponents/Select";
import Button from "./FormComponents/Button";
class FormContainer extends Component {
constructor(props) {
super(props);
this.state = {
newUser: {
name: "",
email: "",
location: "",
message: ""
},
locationOptions: ['(outside the USA', 'AL', 'AK', 'AS', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FM', 'FL', 'GA', 'GU', 'HI',
'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MH', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV',
'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'MP', 'OH', 'OK', 'OR', 'PW', 'PA', 'PR', 'RI', 'SC', 'SD', 'TN', 'TX',
'UT', 'VT', 'VI', 'VA', 'WA', 'WV', 'WI', 'WY' ]
};
this.handleTextArea = this.handleTextArea.bind(this);
this.handleFullName = this.handleFullName.bind(this);
this.handleEmailAddress = this.handleEmailAddress.bind(this);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.handleClearForm = this.handleClearForm.bind(this);
this.handleInput = this.handleInput.bind(this);
}
为什么当点击“提交”按钮时什么也没发生?
答案 0 :(得分:0)
handleFormSubmit(e) {
e.preventDefault();
let userData = this.state.newUser;
fetch('http://formspree.io/myAddress@gmail.com', {
method: "POST",
body: JSON.stringify(userData),
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
}).then(response => {
response.json().then(data => {
console.log("Successful" + data);
});
}).catch(error => {
console.log('post error', error);
});
}
您应该能够看到问题所在。