使用 React 和 Web 组件

IT技术 javascript html reactjs ecmascript-6 web-component
2021-05-19 01:11:53

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

HTML 会像

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

pageInfo并且mediaInfo将是将在全局窗口范围内声明的 JS 对象,或者它们可以在其他一些命名空间/对象内,在这种情况下,HTML 将类似于

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

或者

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

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

目前呈现和注册自定义元素的代码是,

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

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

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

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

2个回答

不使用 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;
}

如果getAllProps()返回一个对象,并且该对象中的每个属性都是您想要的props,您应该只需要更新您的渲染以使用扩展运算符(...)。这将解构您的对象,以便将每个属性App作为prop.

这是它的样子:

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