简体   繁体   中英

React.js component syntax error (Unexpected token) that I cannot find

Hey everyone and thanks for helping. While updating my ruby on rails app from rails v5.0 to 6,0, I've encountered an error with one of my react components and despite the fact I tried to fix it with many JS linters. I couldn't find any proper solution.

That's the output I get:

SyntaxError: unknown: Unexpected token (3:8)
  1 | class AvatarUploadInline extends React.Component {
  2 | 
> 3 |   state = { url: this.props.url };
    |         ^
  4 | 
  5 |   trigger = (event) => {
  6 |     event.preventDefault();

And this is the component itself:

class AvatarUploadInline extends React.Component {

  state = { url: this.props.url };

  trigger = (event) => {
    event.preventDefault();
    $("#artist_avatar").click();
  }

  showPreview = (changeEvent) => {
    changeEvent.preventDefault();
    var reader = new FileReader();
    reader.onload = (fileReadEvent) => {
      this.setState({ url: fileReadEvent.target.result });
    };
    reader.readAsDataURL(changeEvent.target.files[0]);
  }

  render () {
    return <div className="m-form__upload-avatar">
      <input name="artist[avatar]" id="artist_avatar" type="file" onChange={this.showPreview} />
      <span id="avatar" style={{ backgroundImage: `url(${this.state.url})` }} className="m-form__upload-avatar__image" />
      <span className="m-form__upload-avatar__icon" onClick={this.trigger} />
    </div>;
  }
}

Many thanks for your assistance!

You can edit your.babelrc file to be able to use this syntax. This ll solve your issues at other places as well like functions.

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

As described on React documentation, create a constructor and initialize your state there to avoid bugs.

Like this:

class AvatarUploadInline extends React.Component {

 constructor(props) {
  super(props);
  this.state = {
   url: props.url
  }
 }
 ...
}

You can read more about here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM