Exporting a default & declaring anon function all

2020-02-15 08:08发布

Here's an example of something I want to do and currently throws an error. I'm not sure I understand why, but it's not syntactically correct to export, assign default, and assign a variable on one line. The benefit of having it be an anon function is that i can use the fat arrow => and open up a return value with ( and ) instead of opening { and } to return jsx.

export default let Checkbox = (props) => (
  <div style={styles.checkboxContainer}>
    <input styleName={styles.checkbox} type="checkbox" />
    <span styleName={styles.checkboxStyled}></span>
  </div>
)

Is there a way to do this all in one line? Is there a good reason why I can't / why it's not in the spec?

1条回答
Anthone
2楼-- · 2020-02-15 08:52

You can do that for named exports if you want, but not for default ones.

Your alternatives are:

  • Don't declare a variable. After all, you just want to export a single value:

    export default (props) => (
        …
    );
    
  • Declare the variable and export it in two separate declarations:

    let Checkbox = (props) => (
        …
    );
    export default Checkbox;
    

    If you need to bind to the variable because you want to (re)assign to it (as let suggests), use

    export {Checkbox as default};
    
  • Use a proper function declaration (which binds the local variable as well):

    export default function Checkbox(props) {
        return …
    }
    

    If you don't need that, you can also export an unnamed function declaration.

查看更多
登录 后发表回答