首页 > 解决方案 > 如何呈现作为键值保存的组件列表

问题描述

我有以下 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} 的对象)。如果您打算渲染一组子项,请改用数组。

但是上面所有的组件都是一个数组。

我能否请您对此提出一些建议。

标签: javascriptreactjs

解决方案


返回的数组中存储的 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>


推荐阅读