eig*_*nts 6 javascript babel ecmascript-6 reactjs
我有一个使用reactjs的项目,这是由babel编译的.我使用es2015并在我的反应中做出反应.babelrc.我目前正在重构,在我的第一遍中,我基本上做export class foo了我需要的一切.很多这些类应该只是函数,所以我试图重写它们,但我一直得到同样的错误.我的主应用程序文件看起来像这样的东西:
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
Run Code Online (Sandbox Code Playgroud)
我的导入ui.js是这样的:
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
)
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试将其中一个导出的类更改为函数时,例如:
// Note: I have tried a variety of syntax such as function, const, etc...
export var Bar {
render() {
return (
// Some other JSX
)
}
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
SyntaxError: Unexpected token <line where I declare a function>
Run Code Online (Sandbox Code Playgroud)
我不确定我做错了什么,我的谷歌搜索只能得到其他问题的答案.
导出函数与导出类没有什么不同。必须遵守基本规则。
请参阅下面显示返回的多个函数的示例。
import React from 'react';
/* All function / class names HAS TO BE in CAPS */
var App1 = function (){
return (
<div>
<h1>
Hello World
</h1>
</div>
)
}
var App2 = function (){
return (
<div>
<h1>World Number 2 </h1>
</div>
);
}
var AllApp = function (){
return (
<div>
<App1 />
<App2 />
</div>
);
}
export default AllApp;
Run Code Online (Sandbox Code Playgroud)
我的 index.js 文件:
import React from 'react';
import ReactDOM from "react-dom";
import AllApp from "./classhouse.jsx"; /* Note: App name has to be in CAPS */
import App from "./App";
const jsx =
<div>
<AllApp />
<App />
</div>
ReactDOM.render(jsx, document.getElementById("root"));
Run Code Online (Sandbox Code Playgroud)
它与将函数定义为变量相同,只是将导出添加到前面,例如(使用ES6语法)
export const render = () => (
// Some other JSX
);
Run Code Online (Sandbox Code Playgroud)
或者
export var render = function() {
return (
// Some other JSX
);
};
Run Code Online (Sandbox Code Playgroud)