javascript - 使用 React 和 Web 组件

标签 javascript html reactjs ecmascript-6 web-component

在我们的项目中,我们使用 React 和 Web Components 来开发可重用的 UI 组件(这些组件将由内部的各种开发团队使用)。组件在 React 中开发,并通过 Web 组件注册为自定义 HTML 元素。我们需要一种方法,通过它我们可以在 HTML 自定义标签中定义 Prop 并访问我们的 React 组件中的所有 Prop 。

HTML 会像

<custom-element props1='pageInfo' props2='mediaInfo'></custom-element>

pageInfomediaInfo 将是 JS 对象,它们将在全局窗口范围内声明,或者它们可以在其他一些 namespace /对象中,在这种情况下,HTML 将是像

<custom-element props1='NS.pageInfo' props2='NS.mediaInfo'></custom-element>

<custom-element props1='NS.Page.pageInfo' props2='NS.Media.mediaInfo'></custom-element>

因此,我们需要一种方法来获取 HTML 中定义的所有 Prop 并将它们解析为对象并将其传递给 ReactDOM.render

目前渲染和注册自定义元素的代码是,

class RegComponent extends HTMLElement {
    constructor() {
        super();
    }
    createdCallback() {
        ReactDOM.render(<App props1={eval(this.getAttributes('props1'))}/>, this);
    }
}
document.registerElement('custom-element', RegComponent);

我们想摆脱 eval,所有声明的 Prop 都应该从 HTML 中获取并传递给 ReactDOM.render。寻找类似的东西,

ReactDOM.render(<App {getAllProps()}/>, this);

getAllProps() 应该返回所有 Prop 名称及其值(value)。请记住,我使用的是 ES6。任何帮助将不胜感激!

最佳答案

如果不使用 JSX 呢:

ReactDOM.render(<App props1={eval(this.getAttributes('props1'))}/>, this);

直接使用 React,通过适配器将属性转换为 props:

ReactDOM.render(React.createElement(App, {...getAllProps(this.attributes)}), this);

function getAllProps(attributes) {
    var props = {};
    for (var i = 0; i < attributes.length; i++) {
        props[attributes[i].nodeName] = attributes[i].nodeValue;
    }
    return props;
}

关于javascript - 使用 React 和 Web 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37026656/

相关文章:

reactjs - 如何在 React Material UI 中为属性添加 css

javascript - 快速 : What Format is the Date in this JSON file

java - 获取网页内容 - 浏览器不支持框架

javascript - 位置随机形状

html - 显示 2 个边框,文本居中

javascript - Nodejs 网站 + React

javascript - 如何在 ASP.NET Web 表单中的特定 jQuery UI 选项卡中触发回发

javascript - React native 无法将读取权限(电子邮件)传递给发布授权请求

javascript - 在同一函数中调用 `Function` 与 `Function()`

javascript - React - 在默认值更改时执行函数