我正在使用React迈出第一步,并停留在从简单的用户注册表单到后端API的POST-ing数据上。由于某些原因,当我按下表单中的“注册”按钮并想调用handleSubmit
时,它不会被调用而是抛出一些错误。
import React, { Component } from 'react';
import axios from 'axios';
import { Container, Row, Col } from 'reactstrap';
import NavBar from '../NavBar';
class RegistrationForm extends Component {
constructor(props)
{
super(props)
this.state = {
name: '',
display: '',
email: '',
pswd: ''
}
console.log("RegistrationForm constructor");
};
changeNameValue = (e) => { this.setState({ name: e }) }
changeDisplayValue = (e) => { this.setState({ display: e }) }
changeEmailValue = (e) => { this.setState({ email: e }) }
changePswdValue = (e) => { this.setState({ pswd: e }) }
handleSubmit = () => {
console.log("handleSubmit()");
const data = {
username: this.state.name,
displayname: this.state.display,
email: this.state.email,
password: this.state.pswd
}
axios.post(
'http://localhost:9000/api/registeruser',
{ body: JSON.stringify(data) }
).then(res => console.log("Posted"));
}
render() {
var logoImage = require('../../images/logo_v3_150.png');
return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<Container>
<Row>
<img src={logoImage} width='150' height='184' /><br />
</Row>
<Row>
<form>
<input value={this.state.name} onChange={(e) => this.changeNameValue(e.target.value)} placeholder='Username' /><br />
<input value={this.state.display} onChange={(e) => this.changeDisplayValue(e.target.value)} placeholder='Display Name' /><br />
<input value={this.state.email} onChange={(e) => this.changeEmailValue(e.target.value)} placeholder='Email' /><br />
<input value={this.state.pswd} onChange={(e) => this.changePswdValue(e.target.value)} placeholder='Password' /><br />
<button onClick={this.handleSubmit}>Register</button>
</form>
</Row>
<Row>
<NavBar />
</Row>
</Container>
</div>
);
}
}
export default RegistrationForm;
这可能是我想念的愚蠢之举,但我自己无法弄清楚。