使用React和Web Components [英] Using React and Web Components

查看:359
本文介绍了使用React和Web Components的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In our project we are using React and Web Components to develop reusable UI components (which in turn will be used by various dev teams internally). Components are developed in React and registered as custom HTML elements through Web Components. We need a way through which we can define the props in HTML custom tag and access all the props in our React Component.

HTML将像

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

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

pageInfo and mediaInfo will be JS Objects which will be declared in global window scope or they can be inside some other NameSpace/Object, in that case the HTML would be something like

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

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

所以,我们需要一种方式来获取HTML中定义的所有道具,并解决它们作为对象并将其传递给 ReactDOM.render

So, we need a way to get all the props defined in the HTML and resolve them as Objects and pass it on to ReactDOM.render

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

Currently the code to render and register custom element is,

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

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

We want to get rid of eval and all the declared props should be fetched from HTML and passed on to ReactDOM.render. Looking for something like,

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

其中 getAllProps()应该返回所有道具名称他们的价值。记住我正在使用ES6。任何帮助将不胜感激!

where getAllProps() should return all the props name & their value. Remember that I'm using ES6. Any help would be appreciated!

推荐答案

而不是使用JSX:

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

直接使用React,将适配器转换成道具:

Use React directly, with an adapter transforming attributes into 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;
}

这篇关于使用React和Web Components的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆