React-如何导出纯无状态组件

如何导出无状态的纯哑组件?

如果我使用类,这是有效的:

import React, { Component } from 'react';


export default class Header extends Component {
render(){
return <pre>Header</pre>
}
}

然而,如果我使用一个纯函数,我不能让它工作。

import React, { Component } from 'react';
export default const Header = () => {
return <pre>Header</pre>
}

我是不是漏掉了什么基本的东西?

116077 次浏览

ES6 doesn't allow export default const. You must declare the constant first then export it:

const Header = () => {
return <pre>Header</pre>
};
export default Header;

This constraint exists to avoid writting export default a, b, c; that is forbidden: only one variable can be exported as default

Just as a side note. You could technically export default without declaring a variable first.

export default () => (
<pre>Header</pre>
)

you can do it in two ways

const ComponentA = props => {
return <div>{props.header}</div>;
};


export default ComponentA;

2)

export const ComponentA = props => {
return <div>{props.header}</div>;
};

if we use default to export then we import like this

import ComponentA from '../shared/componentA'

if we don't use default to export then we import like this

import { ComponentA } from '../shared/componentA'

You can also use a function declaration instead of assignment:

export default function Header() {
return <pre>Header</pre>
}

In your example, you already use curly brackets and return so this is apparently matching with your needs with no compromise.