使用reactjs和babel导出函数 [英] Exporting functions with reactjs and babel
问题描述
我有一个使用reactjs的项目,该项目由babel编译.我使用es2015并在 .babelrc
中响应转换.我目前正在重构,在我的第一遍中,我基本上对所需的所有内容都做了 export class foo
.这些类中的许多实际上应该只是函数,因此我试图照原样重写它们,但我一直遇到相同的错误.我的主应用程序文件看起来像这样:
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
我从 ui.js
导入的内容是这样的:
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
)
}
}
我收到以下错误:
SyntaxError: Unexpected token <line where I declare a function>
我不确定自己做错了什么,我的Google搜索仅能找到其他问题的答案.
I am not sure what I am doing wrong, and my google searches are only coming up with answers to other problems.
推荐答案
与将函数定义为变量相同,只是将export添加到前面,例如(使用ES6语法)
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
);
或者
export var render = function() {
return (
// Some other JSX
);
};
这篇关于使用reactjs和babel导出函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!