为什么需要在父组件和子组件中多次导入React? [英] Why do you need to import React multiple times in parent and child components?
问题描述
如果您的父组件文件已经导入 React
,为什么它的任何渲染子文件也需要导入React?它是否只是一个安全措施,以防那些孩子被渲染到React尚未导入的其他地方?
If you have a parent component file that already imports React
, why does any of its rendered children files also need to import React? Is it just a safety measure in case those children are ever rendered somewhere else where React has not been imported yet?
推荐答案
在 nodejs
每个文件都是一个模块,它有自己的变量范围。将变量导入文件(例如 React
)时,将此变量添加到模块范围,但不添加到全局范围。
In nodejs
each file is a module, that has its own scope of variables. When you import variable into file (React
for example) you add this variable to the module scope, but not to the global scope.
如果是 webpack
,你可以使用 providePlugin
轻松使 React
变量全局:
In case of webpack
you can use providePlugin
to easily make React
variable global:
new webpack.ProvidePlugin({
React: 'react' // ReactJS module name in node_modules folder
})
之后,您可以跳过导入 React
变量模块。 Webpack
将在需要时自行完成。
After that you are able to skip importing React
variable in all of your modules. Webpack
will do it itself where needed.
这篇关于为什么需要在父组件和子组件中多次导入React?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!