Exporting a default & declaring anon function all in one

笑着哭i 提交于 2019-12-18 09:39:00

问题


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:


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.



来源:https://stackoverflow.com/questions/34102534/exporting-a-default-declaring-anon-function-all-in-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!