在我们的项目中,我们使用 React 和 Web Components 来开发可重用的 UI 组件(这些组件将由内部的各种开发团队使用)。组件在 React 中开发,并通过 Web 组件注册为自定义 HTML 元素。我们需要一种方法,通过它我们可以在 HTML 自定义标签中定义 Prop 并访问我们的 React 组件中的所有 Prop 。
HTML 会像
<custom-element props1='pageInfo' props2='mediaInfo'></custom-element>
pageInfo
和 mediaInfo
将是 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/