class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
name: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({name: event.target.value});
}
handleSubmit(event) {
event.preventDefault();
fetch('/submit-form', {
method: 'POST',
body: JSON.stringify(this.state)
}).then(response => {
console.log(response.json());
}).catch(error => {
console.error(error);
});
}
render() {
return (
);
}
}
这个React表单演示使用了fetch API提交到服务器。如果提交失败,浏览器将会在控制台输出错误,以帮助调试问题。