首页 > 解决方案 > 导入Web组件以响应应用程序时如何使用数组对象

问题描述

我将此https://www.npmjs.com/package/vue-advanced-chat包作为 Web 组件导入到我的反应项目中。在我想将一个数组对象传递给组件之后,我该怎么做?我不能像房间一样使用= {房间}

我的代码

import React from "react";
import "../../../node_modules/vue-advanced-chat/dist/vue-advanced-chat.js";

function test() {
    const room = [
        {
            roomId: 1,
            roomName: "Room 1",
           
        }
    ];
    const messages = [];

    return (
        <div>
            <vue-advanced-chat currentUserId="12" rooms={ room }></vue-advanced-chat>
        </div>
    );
}
export default test;

标签: reactjsvue.jsweb-component

解决方案


React 不支持props直接传递给 Web 组件。这是即将到来的 React 短板之一。它只支持将属性(字符串/数字)传递给 Web 组件。您将不得不使用 Reactref来强制执行此操作。以下是使用hooksTest的示例组件。

function Test() {
  const [rooms, setRooms] = useState([
    {
      roomId: 1,
      roomName: "Room 1",
        
    }
  ]);

  const messages = [];

  // hook to maintain chat component instance
  const chatElm = useRef(null);

  useEffect(() => {
    if (chatElm.current) {
      // Update the rooms property of the chat web component imperatively
      chatElm.current.rooms = rooms;
    }
  }, [rooms]);

  return (
    <div>
      <vue-advanced-chat ref={chatElm} currentUserId="12"></vue-advanced-chat>
    </div>
  );
}

阅读React Web 组件文档以获取更多信息。


推荐阅读