React - 初始化状态时出现“意外令牌”

IT技术 reactjs semantic-ui
2021-05-13 15:38:19

我对 React 还很陌生,所以请原谅这个问题中的任何错误!

我目前正在尝试使用基本的登录表单:

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;

我面临的问题是该state = { username: '', password: '' }行产生以下错误:

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)

我从这里复制了这个,但即使是那里的代码片段也会给我这个错误。我错过了什么?:(

3个回答

正如在 github上的类似问题中提到的您应该编辑.babelrc文件才能使用此语法。

{
  "presets": [
    ["es2016"],
    "react"
  ],
  "plugins": [
    "babel-plugin-transform-class-properties"
  ]
}

将其包含在构造函数中。而且您还需要使用关键字将您的状态绑定到您的组件

  constructor() {
    super();
    this.state = {
      username: '', password: ''
    };
  }

你没有nameInput属性

<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}/>