Import statements: with or without React?

前端 未结 2 1089
甜味超标
甜味超标 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 = <div />
    

    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.

    0 讨论(0)
  • 2021-01-11 15:50

    Use option 1 because babel will transform your jsx
    <button onClick={action}>Submit</button>
    to
    React.createElement("button", { onClick: action }, "Submit");

    So as you see react must be in scope. You have two options:

    1. import React from 'react';
    2. or define React globally
    0 讨论(0)
提交回复
热议问题