reactjs - 导入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;
解决方案
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 组件文档以获取更多信息。
推荐阅读
- pid - 使用 Modelica 模型和 PID 控制器设计进行过程识别
- performance - GCP 不同地区 N2 sku 的不同性能水平
- android - 试图避免泛型:“类 Result 需要一个类型参数
" - winapi - 如何判断窗口句柄是否是主窗口句柄?
- amazon-web-services - aws 代码构建、代码部署、CI/CD 管道错误
- excel - 通过用户表单在某行中使用 VBA 代码填充数据
- git - Github 所有的拉取请求都转到上游而不是当前的分叉
- javascript - D3 饼图仅以一种颜色呈现
- python - 为什么我不断收到此“没有名为 utils 的模块”错误?
- node.js - MongoDB过滤器聚合