这是我用于自定义Web组件创建的代码。
import S3Uploader from 'containers/S3Uploader';
import React from 'react';
import * as ReactDOM from "react-dom";
class Component extends HTMLElement {
constructor() {
super();
}
detachedCallback() {
ReactDOM.unmountComponentAtNode(this);
}
createdCallback() {
console.log("This attributes",this.attributes); //Why the attribute length is 0
const props = this.getAllProps(this.attributes);
console.log(props);
const s3Config = JSON.parse(this.getAttribute('s3-config')); //This is null
const handleUpload = eval(this.getAttribute('handle-upload'));
console.log(s3Config,handleUpload);
ReactDOM.render(<S3Uploader s3Config={s3Config} handleUpload={handleUpload}/>, this);
}
getAllProps(attributes) {
let props = {};
for (let i = 0; i < attributes.length; i++) {
props[attributes[i].nodeName] = attributes[i].nodeValue;
}
return props;
}
}
document.registerElement('s3-uploader',Component);
问题在于属性长度为0,并且createdCallback函数中的所有属性均为空。
因此,我无法传递所需的属性来响应组件。
答案 0 :(得分:2)
尝试转换为V1规格而不是V0规格:
//import S3Uploader from 'containers/S3Uploader';
//import React from 'react';
//import * as ReactDOM from "react-dom";
class Component extends HTMLElement {
constructor() {
super();
}
disconnectedCallback() {
//ReactDOM.unmountComponentAtNode(this);
}
connectedCallback() {
console.log("Attribute count",this.attributes.length); //Why the attribute length is 0
const props = this.getAllProps(this.attributes);
console.log(props);
const s3Config = JSON.parse(this.getAttribute('s3-config')); //This is null
const handleUpload = eval(this.getAttribute('handle-upload'));
console.log(s3Config,handleUpload);
//ReactDOM.render(<S3Uploader s3Config={s3Config} handleUpload={handleUpload}/>, this);
}
getAllProps(attributes) {
let props = {};
for (let i = 0; i < attributes.length; i++) {
props[attributes[i].nodeName] = attributes[i].nodeValue;
}
return props;
}
}
customElements.define('s3-uploader',Component);
<s3-uploader s3-config='{"dog":12}' handle-upload="console.log('testing')"></s3-uploader>
我注释掉了反应代码,因此它可以在测试台上运行,但是可以。
V0规范已弃用,不久将失效。所有组件都应使用V1规范编写。