javascript - 如何呈现作为键值保存的组件列表
问题描述
我有以下 React 组件列表,无法更改此格式。
我怎样才能通过以某种方式循环在我的页面上呈现这个列表?
const allComponents = isValid => [
{
Component: (
<ComponentA
isTransparent={true}
/>
),
},
{
Component: (
<div>
{<ComponentB/>}
</div>
),
},
!isValid && {
Component: (
<div>
{<ComponentC/>}
</div>
),
},
].filter(Boolean);
在我的返回块中尝试了以下操作:
return (
<Fragment>
{allComponents(false).map(c => (
{c}
))}
</Fragment>
);
最终出现以下错误。
错误!对象作为 React 子级无效。
(找到:带有键 {c} 的对象)。如果您打算渲染一组子项,请改用数组。
但是上面所有的组件都是一个数组。
我能否请您对此提出一些建议。
解决方案
返回的数组中存储的 JSXallComponents()
需要从有效的函数组件中返回。您可以将Component
属性转换为函数
{
Component: () => (
<ComponentA />
),
},
// And then call it in the map()
{allComponents(false).map(c => (
c.Component()
))}
或从调用中的IIFE返回 JSXmap()
{allComponents(false).map(c => (
(() => c.Component)()
))}
工作片段
const App = () => {
const allComponents = isValid => [
{
Component: (
<ComponentA />
)
,
},
{
Component: (
<div>
{<ComponentB />}
</div>
)
,
},
!isValid && {
Component: (
<div>
{<ComponentC />}
</div>)
,
},
].filter(Boolean);
return (
<div>
<p>isValid: False</p>
<div>
{allComponents(false).map(c => (
(() => c.Component)()
))}
</div>
<p>isValid: True</p>
<div>
{allComponents(true).map(c => (
(() => c.Component)()
))}
</div>
</div>
);
}
const ComponentA = () => {
return (
<div>Component A</div>
)
}
const ComponentB = () => {
return (
<div>Component B</div>
)
}
const ComponentC = () => {
return (
<div>Component C</div>
)
}
ReactDOM.render(
<App />,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
推荐阅读
- java - Android studio java.lang.NoSuchMethodError: 没有静态方法 encodeBase64URLSafeString([B)Ljava/lang/String;
- c# - 信号量不增加或减少
- php - Codeigniter - 遇到 PHP 错误未定义的变量:home_post
- php - 更新负载均衡器后面所有服务器上的路由缓存
- xamarin - 处理 Xamarin.ios 中的部分 CloudKit 错误
- fortran - Fortran:如果语句在同一行上有两个命令
- reactjs - RTL getBy 方法后跟 toBeInDocument
- android - Android Koin DI 无法获取命名实例
- angular - 如何将电子邮件发送到我们应用程序中添加的电子邮件
- python - pygal.worldmap 没有关联代码且未启用的国家/地区更改字体大小