问题
I'm fairly new to React, so please forgive any errors in this question!
I'm currently trying to get a basic login form working:
import React, { Component } from 'react';
import { Input, Form, Button } from 'semantic-ui-react'
class LoginForm extends Component {
state = { username: '', password: '' }
handleChange = (e, { name, value }) => this.setState({ [name]: value })
handleSignIn(e) {
e.preventDefault()
this.props.onSignIn(this.username, this.password)
}
render() {
const { username, password } = this.state
return (
<div className="login-container">
<Form onSubmit={this.handleSignIn.bind(this)}>
<Form.Field>
<Input icon="user" iconPosition="left" placeholder="Username" type="text" ref="username" onChange={this.handleChange}/>
</Form.Field>
<Form.Field>
<Input icon="user secret" iconPosition="left" placeholder="Password" type="password" ref="password" onChange={this.handleChange}/>
</Form.Field>
<Form.Field>
<Button type="submit" className="inputSpacing" color="yellow"><Icon name='lock' />Login</Button>
</Form.Field>
</Form>
</div>
);
}
}
export default LoginForm;
The issue that I'm facing is that the state = { username: '', password: '' }
line generates the following error:
ERROR in ./react-client/src/components/coreComponents/loginForm.js
Module build failed: SyntaxError: D:/path/to/project/react-client/src/components/coreComponents/loginForm.js: Unexpected token (6:8)
I've copied this from here, but even the code snippets there give me this error. What am I missing? :(
回答1:
As mentioned on a similar issue on github. You should edit your .babelrc file to be able to use this syntax.
{
"presets": [
["es2016"],
"react"
],
"plugins": [
"babel-plugin-transform-class-properties"
]
}
回答2:
Enclose it within a constructor. And also you need to bind your state to your component with this keyword
constructor() {
super();
this.state = {
username: '', password: ''
};
}
回答3:
You don't have name
properties for your Input
's.
<Input name="username" icon="user" iconPosition="left" placeholder="Username" type="text" ref="username" onChange={this.handleChange}/>
<Input name="password" icon="user secret" iconPosition="left" placeholder="Password" type="password" ref="password" onChange={this.handleChange}/>
来源:https://stackoverflow.com/questions/51956481/react-unexpected-token-when-initialising-state