简体   繁体   中英

Outputting variable in react component

I am trying to out a variable in a component however I am getting the following error,

Invalid regular expression: missing /

My code is as follows,

class Profile extends React.Component {
  constructor() {
    super();
    this.state = {
      user:user
    }
    this.updateAvatar = this.updateAvatar.bind(this);
    this.formatName = this.formatName.bind(this);
  }

  render() {
    let user_name = this.formatName(this.state.user.first_name, this.state.user.last_name);
    console.log(user_name);
    return (
      <Avatar image={this.state.user.avatar}
              changeImageOnClick={this.updateAvatar} />
      <p>{ user_name }</p>
    )
  }

  formatName(first_name, last_name) {
    console.log(first_name);
    return first_name + " " + last_name;
  }

  updateAvatar() {
      this.setState({user:{avater:'new'}})
  }
}

Cant understand why I would be getting this error, this should be so simple to do :(

You can't return two nodes on the same level. Just one, so you need to wrap it. Try this:

class Profile extends React.Component {
  constructor() {
    super();
    this.state = {
      user:user
    }
    this.updateAvatar = this.updateAvatar.bind(this);
    this.formatName = this.formatName.bind(this);
  }

  render() {
    let user_name = this.formatName(this.state.user.first_name, this.state.user.last_name);
    console.log(user_name);
    return (
      <div>
        <Avatar image={this.state.user.avatar}
                changeImageOnClick={this.updateAvatar} />
        <p>{ user_name }</p>
      </div>
    )
  }

  formatName(first_name, last_name) {
    console.log(first_name);
    return first_name + " " + last_name;
  }

  updateAvatar() {
      this.setState({user:{avater:'new'}})
  }
}

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