我有以下的反应组件列表,无法更改此格式。
如何在页面上以某种方式循环显示此列表?
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}的对象)。如果您打算呈现一个子集合,请使用数组代替。
但是上面的allComponents是一个数组。
请给我一些建议好吗?
发布于 2021-07-16 16:02:54
存储在allComponents()
返回的数组中的JSX需要从有效的函数组件返回。您可以将Component
属性转换为函数。
{
Component: () => (
<ComponentA />
),
},
// And then call it in the map()
{allComponents(false).map(c => (
c.Component()
))}
或者从生平返回map()
调用中的JSX
{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>
https://stackoverflow.com/questions/68411068
复制相似问题