React 的export

用独立文件来写React的组件时,发现个奇怪的事情
export时,如果只导出一个类/函数,貌似必须加default,否则就会报错。

import React from 'react';

class AddByObject extends React.Component {
    constructor(props){
        super(props);
        this.state = {count: 0};
        this.increment = this.increment.bind(this);
    }

    increment() {
        this.setState({
            count: this.state.count + 1
        });

        this.setState({
            count: this.state.count + 1
        });
    }

    render(){
        return (
                

{this.state.count}

); } } export AddByObject
image.png

但如果加上default,就ok了。
这不对啊,ES6里没记得有这规定啊,export default只是默认输出啊,为了能让import随意指定变量名。怎么到了react还有这讲究??

只好网上搜搜了,stackoverlofw里也有人提问,有个点赞多的答案,说这是react的convention,如果导出多个,可以用export {aaa, bbb},如果是从一个文件中导出一个组件,那就需要用default


image.png

好吧,既然是传统,就表示尊重
附上原文链接# Why es6 react component works only with “export default”?

你可能感兴趣的:(React 的export)