Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

javascript - Exporting functions with reactjs and babel

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

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

1 Reply

0 votes
by (71.8m points)

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
  );
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...