Import statements: with or without React?

前端 未结 2 1088
甜味超标
甜味超标 2021-01-11 15:11

There\'s a little bit of a debate at work on whether it is necessary to import React in stateless components and I can\'t find any docs about it. So:

         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-11 15:36

    It depends on how you're building your files. If you're using a module bundler like webpack and there's no notion of a global React module then leaving out React will throw the error React is not defined.

    This is because this:

    let C = 

    turns into:

    let C = React.createElement("div", null)
    

    So inside that particular module.. React is not imported and therefore will trip on the undefined variable.

    You can expose React to the window namespace, then you don't need to import it into every file. That's up to you.

提交回复
热议问题