小编jeh*_*ert的帖子

对从索引文件导入的 React 组件进行样式化时出错,但直接从组件文件导入时不会出错

这里是新手,所以如果我忽略了一些明显的东西或错过了重复的帖子(并且也没有直接在样式组件上发布,显然我需要一个代表......),请提前道歉。

\n\n

我发现最接近我的问题的是这个已解决的问题,位于线程的底部:\n https://github.com/styled-components/styled-components/issues/213

\n\n

这个人有一个非常相似的问题,但解决方案很简短并且特定于 Typescript。

\n\n

背景:我有一个索引文件,它从各地导入我的组件,并以 webpack 别名导出它们。每当我需要在其他地方导入时,我只需声明:

\n\n
import { MyComponentA, MyComponentB, MyComponentC } from \'components\';\n
Run Code Online (Sandbox Code Playgroud)\n\n

我最近开始将样式化组件合并到我的项目中,当我尝试对以这种方式导入的组件进行样式化时,出现了如下错误:

\n\n
Error: Cannot create styled-component for component: undefined._____________styled-components.browser.esm.js:233\n   at new StyledComponentsError (/home/jhillert/Dropbox/Projects/TimeLockr/node_modules/styled-components/dist/styled-components.browser.esm.js:233:59)\n   at constructWithOptions (/home/jhillert/Dropbox/Projects/TimeLockr/node_modules/styled-components/dist/styled-components.browser.esm.js:1355:12)\n   at styled (/home/jhillert/Dropbox/Projects/TimeLockr/node_modules/styled-components/dist/styled-components.browser.esm.js:2293:11)\n   at Module.eval (/home/jhillert/Dropbox/Projects/TimeLockr/src/components/card-area/CardArea.jsx:111:91)\n   at eval (/home/jhillert/Dropbox/Projects/TimeLockr/src/components/card-area/CardArea.jsx:133:31)\n   at Module../src/components/card-area/CardArea.jsx (http://localhost:8080/bundle.js:9343:1)\n   at __webpack_require__ (http://localhost:8080/bundle.js:724:30)\n   at fn (http://localhost:8080/bundle.js:101:20)\n   at eval (/home/jhillert/Dropbox/Projects/TimeLockr/src/indexes/components.jsx:17:89)\n   at Module../src/indexes/components.jsx (http://localhost:8080/bundle.js:9619:1)\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果我直接从源文件导入组件,则不会收到错误。仅当我尝试将从索引文件导入的组件传递到 styled() 方法中,以及当我尝试使用 CSS prop 添加内联样式时,才会发生这种情况。

\n\n

由于某种原因,以这种方式导入的所有组件都不会发生错误,而且我对代码进行了更改,突然导致索引导入触发错误。我真的很喜欢有一个中央索引文件,所以修复将不胜感激。

\n\n

css prop 导致错误的示例:

\n\n

*项目配置如下。\n索引文件如下所示 (components.jsx):

\n\n
export { …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs webpack styled-components

4
推荐指数
1
解决办法
9459
查看次数

标签 统计

javascript ×1

reactjs ×1

styled-components ×1

webpack ×1