简体   繁体   English

动态导入的 React 组件的样式组件警告

[英]Styled Components warning for dynamically imported React components

From a headless CMS I'm fetching the list of components which should be included on certain page.我从无头 CMS 中获取应包含在特定页面上的组件列表。 Once fetched, I dynamically import mentioned components like this:获取后,我会动态导入提到的组件,如下所示:

const components = ["Test", "Test2"]; // comes from CMS

const DynamicComponent = ({ name }) => {
   let Component;
   Component = require(`./components/${name}`).default;
   return <Component />;
};

export default function App() {
   return (
      <Container>
         {components.map((comp, i) => (
         <DynamicComponent name={comp} key={i} />
          ))}
      </Container>
   );
}

And then I just pass these component as children props to some container.然后我只是将这些组件作为子道具传递给某个容器。

However, although everything works fine, I'm getting some warning for every component I have that says:但是,虽然一切正常,但我收到的每个组件都收到了一些警告,上面写着:

The component styled.div with the id of "sc-bdnylx" has been created dynamically. id 为“sc-bdnylx”的组件 styled.div 已动态创建。 You may see this warning because you've called styled inside another component.您可能会看到此警告,因为您在另一个组件中调用了 styled。 To resolve this only create new StyledComponents outside of any render method and function component.要解决此问题,只需在任何渲染方法和功能组件之外创建新的 StyledComponent。

I googled the warning but everywhere the solution is to not define styles within the component.我在 google 上搜索了警告,但到处都是解决方案,即不在组件中定义样式。 I could be wrong, but I don't think that's applicable here.我可能是错的,但我认为这不适用于这里。

Here's the full example: https://codesandbox.io/s/style-components-dynamic-5id3y?file=/src/App.js (check the console output)这是完整示例: https : //codesandbox.io/s/style-components-dynamic-5id3y?file=/src/App.js (检查控制台输出)

How can I get rid of this warning?我怎样才能摆脱这个警告?

Thank you谢谢

Well, the warning is pretty clear when it says "create new StyledComponents outside of any render method and function component ".好吧,当它说“在任何渲染方法和函数组件之外创建新的 StyledComponents”时,警告非常清楚。 So what you can do is refactor your functional component DynamicComponent into a class based component所以你可以做的是将你的功能组件DynamicComponent重构为一个基于类的组件

class DynamicComponent extends React.Component {
  constructor(props) {
    super(props);
    this.Component = require(`./components/${this.props.name}`).default;
  }
  render() {
    return <this.Component />;
  }
};

EDIT: tested on your sandbox, made the fixes to my previous code, and your warnings are gone编辑:在您的沙箱上进行了测试,对我以前的代码进行了修复,并且您的警告消失了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM