在我们的项目中,我们使用React和Web组件来开发可重用的UI组件(这些组件反过来将由不同的开发团队在内部使用)。组件在React中开发,并通过Web组件注册为自定义HTML元素。我们需要一种方法来定义HTML自定义标记中的道具,并访问我们的React组件中的所有道具。
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>
因此,我们需要一种方法来获取在ReactDOM.render
中定义的所有支持,并将它们解析为对象,并将其传递给。
当前呈现和注册自定义元素的代码是,
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
。寻找类似的东西,
ReactDOM.render(<App {getAllProps()}/>, this);
getAllProps()
应该返回所有的道具名称&它们的值。记住,我使用的是ES6。任何帮助都将不胜感激!
发布于 2016-05-13 12:26:46
不如不要使用JSX:
ReactDOM.render(<App props1={eval(this.getAttributes('props1'))}/>, this);
直接使用React,适配器将属性转换为支持:
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;
}
发布于 2016-05-04 05:02:47
如果getAllProps()
返回一个对象,并且该对象中的每个属性都是您想要的支柱,则只需更新呈现以使用扩展运算符(...
)。这将解构您的对象,以便将每个属性作为prop
传递给prop
。
以下是它的样子:
ReactDOM.render(<App {...getAllProps()}/>, this);
https://stackoverflow.com/questions/37026656
复制