![](/img/trans.png)
[英]react, styled-components - setting props on a imported styled div
[英]Styled Components warning for dynamically imported React components
我從無頭 CMS 中獲取應包含在特定頁面上的組件列表。 獲取后,我會動態導入提到的組件,如下所示:
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>
);
}
然后我只是將這些組件作為子道具傳遞給某個容器。
但是,雖然一切正常,但我收到的每個組件都收到了一些警告,上面寫着:
id 為“sc-bdnylx”的組件 styled.div 已動態創建。 您可能會看到此警告,因為您在另一個組件中調用了 styled。 要解決此問題,只需在任何渲染方法和功能組件之外創建新的 StyledComponent。
我在 google 上搜索了警告,但到處都是解決方案,即不在組件中定義樣式。 我可能是錯的,但我認為這不適用於這里。
這是完整示例: https : //codesandbox.io/s/style-components-dynamic-5id3y?file=/src/App.js (檢查控制台輸出)
我怎樣才能擺脫這個警告?
謝謝
好吧,當它說“在任何渲染方法和函數組件之外創建新的 StyledComponents”時,警告非常清楚。 所以你可以做的是將你的功能組件DynamicComponent
重構為一個基於類的組件
class DynamicComponent extends React.Component {
constructor(props) {
super(props);
this.Component = require(`./components/${this.props.name}`).default;
}
render() {
return <this.Component />;
}
};
編輯:在您的沙箱上進行了測試,對我以前的代碼進行了修復,並且您的警告消失了
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.