Javascript 使用React和Web组件

Javascript 使用React和Web组件,javascript,html,reactjs,ecmascript-6,web-component,Javascript,Html,Reactjs,Ecmascript 6,Web Component,在我们的项目中,我们使用React和Web组件来开发可重用的UI组件(这些组件将由各个开发团队内部使用)。组件在React中开发,并通过Web组件注册为自定义HTML元素。我们需要一种方法,通过这种方法,我们可以在HTML自定义标记中定义道具,并访问React组件中的所有道具 HTML应该是 <custom-element props1='pageInfo' props2='mediaInfo'></custom-element> 或 我们想摆脱eval,所有声明的道具

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

HTML应该是

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

我们想摆脱eval,所有声明的道具都应该从HTML中获取,并传递到
ReactDOM.render
。寻找像这样的东西

ReactDOM.render(<App {getAllProps()}/>, this);
ReactDOM.render(,this);
其中
getAllProps()
应返回所有道具名称及其值。记住,我正在使用ES6。任何帮助都将不胜感激

如果
getAllProps()
返回一个对象,并且该对象中的每个属性都是所需的道具,则只需更新渲染以使用排列运算符(
)。这将解构对象,以便将每个属性作为
道具
传递给
应用程序

下面是它的样子:


ReactDOM.render(,this)

如何代替使用JSX:

ReactDOM.render(<App props1={eval(this.getAttributes('props1'))}/>, this);
ReactDOM.render(,this);
使用React Direct,通过适配器将属性转换为道具:

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;
}
ReactDOM.render(React.createElement(App,{…getAllProps(this.attributes)}),this);
函数getAllProps(属性){
var props={};
对于(变量i=0;i
我同意spread操作符,但这里的主要问题实际上是如何实现
getAllProps()
,而不是如何使用它。嘿@Aleem,我们也在尝试将React组件呈现为web组件,并且与您的方式类似,但我们缺少一件事:CSS。您如何编写CSS以便将其集成到您的web组件中?@Lukas我们在SASS中编写样式,使用Webpack传输并打包到单独的CSS文件中。您还可以尝试“样式化组件”、“镭”等。您可以将此作为指南,以及@falsarella关于使用JS而不是JSXAnyone的回答在这方面有何进展?如果您想以其他方式使用它,您可以看到此答案
ReactDOM.render(<App {getAllProps()}/>, this);
ReactDOM.render(<App props1={eval(this.getAttributes('props1'))}/>, this);
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;
}