你必须传递一个有效的 ReactElement |甜心反应

You must pass a valid ReactElement | Sweetalert-react

我正在尝试使用 sweetalert-react 包 (https://github.com/chentsulin/sweetalert-react) 作为我的应用程序的模态。 现在我让它工作了,但我希望能够显示一个包含我的组件的常量:

const clusterDoors = lock.doors.map(clusterDoor => {
  return (
    <div key={clusterDoor.port_id}>
      <ClusterListItem
        clusterDoor={clusterDoor}
        customer={
          clusterDoor.allocation.customer ? (
            keyedCustomers[clusterDoor.allocation.customer]
          ) : (
            false
          )
        }
        .....

所以我阅读了他们的文档,发现我可以使用 ReactDOMServer.renderToStaticMarkup 实现这一点。所以我只需要:

text={renderToStaticMarkup(<MyComponent />)}

但问题是我的组件在常量内,所以如果我尝试这样做:

text={renderToStaticMarkup({clusterDoors})}

我会得到错误:

You must pass a valid ReactElement.

我想知道是否有一些解决方法?

我做了一些研究,也尝试过:

const clusterDoors = React.createClass({
  render: function() {
    lock.doors.map(clusterDoor => {
      return (
        <div key={clusterDoor.port_id}>
          <ClusterListItem
            clusterDoor={clusterDoor}
            customer={
              clusterDoor.allocation.customer ? (
                keyedCustomers[clusterDoor.allocation.customer]
              ) : (
                false
              )
            }
            delivery={
              clusterDoor.allocation.delivery ? (
                keyedDeliveries[clusterDoor.allocation.delivery]
              ) : (
                false
              )
            }
          />
        </div>
      )
    })
  }
})

但这并没有起到作用。

如果我向它传递一个有效的 React 组件 (ClusterListItem),我的应用程序不会中断,但不会显示任何内容,因为 array clusterDoor 不存在。

我希望我把我的情况解释清楚了。感谢阅读。

您的代码存在的问题是您传递的是一个元素数组,因为 clusterDoors 是一个数组,而 renderToStaticMarkup 需要一个元素。因此您会收到此错误。

解决方案:只需将您的数组包裹在 div 标记中,使其成为像这样的单个节点元素

text={renderToStaticMarkup(<div>{clusterDoors}</div>)}