Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a project using reactjs, which is transpiled by babel. I use the es2015 and react transforms in my .babelrc. I am currently refactoring and in my first pass I basically did export class foo for everything I needed. A lot of these classes should really just be functions, so I am trying to rewrite them as such, but I keep getting the same error. My main application file looks somethings like this:

import React, { Component } from 'react';

import {Foo, Bar} from './components/ui.js';

class Application extends Component {

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

  componentDidMount(){
    // code
  }

  componentDidUpdate(){
    // other code
  }

  render(){
    return(
      <div>
        <Foo />
        <Bar />
      </div>
    )
  }

}

module.exports = Application

And my import from ui.js is like this:

import React, { Component } from 'react';

export class Foo extends Component {
  constructor(props){
    super(props);
  }

  render() {
    return (
      // Some JSX
    )      
  }
}


export class Bar extends Component {
  constructor(props){
    super(props);

  }

  render() {
    return (
      // Some other JSX
    )      
  }
}

When I try and change one of these exported classes to a function, for example:

// Note: I have tried a variety of syntax such as function, const, etc...
export var Bar {
  render() {
    return (
      // Some other JSX
    )      
  }
}

I get the following error:

SyntaxError: Unexpected token <line where I declare a function>

I am not sure what I am doing wrong, and my google searches are only coming up with answers to other problems.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
157 views
Welcome To Ask or Share your Answers For Others

1 Answer

It's the same as defining the function as a variable but just adding export to the front e.g. (using ES6 syntax)

export const render = () => (
  // Some other JSX
);

or alternatively

export var render = function() {
  return (
    // Some other JSX
  );
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...