I am trying to set the style for an element from a supplied object. like so:
function DOMparseChildren(children: any) {
return children.map((child: any) => {
if(typeof child === 'string') {
return document.createTextNode(child);
}
return child;
})
}
function nonNull(val: any, fallback: any) { return Boolean(val) ? val : fallback };
function DOMparseNode(element: any, properties: any, children: any) {
const el = document.createElement(element) as HTMLElement;
// here it is possible to set style...
// el["style"]["color"] = "red";
Object.keys(nonNull(properties, {})).forEach(key => {
if(key === 'style') {
Object.keys(nonNull(properties[key], {})).forEach(styleKey => {
console.log(element + "." + key + "." + styleKey + " = " + properties[key][styleKey]);
// here it is not possible.......
el[key][styleKey] = properties[key][styleKey];
el["style"]["color"] = "red";
});
}
el[key] = properties[key];
})
DOMparseChildren(children).forEach((child: any) => {
el.appendChild(child);
});
return el;
}
function DOMcreateElement(element: any, properties: any, ...children: any) {
if(typeof element === 'function') {
return element( { ...nonNull( properties, {} ), children } );
}
return DOMparseNode(element, properties, children);
}
usage, it is supposed to help with the following scenario:
document.body.appendChild(<div style={{color: 'red'}}></div>)
the console.log
does log the correct output: h1.style.color = red
So why doesn't it apply my style right below the console.log
??
I don't get any errors.. Which makes debugging so much harder:(
If more context is needed please let me know!
with the ultimate goal being to replace theel["style"]["color"] = "red";
withel[key][styleKey] = properties[key][styleKey];
The line
el[key] = properties[key];
is overwriting all the styles that were set in the properties[key]
loop. You should put that in an else
block so it's only done for non-style
properties.
function DOMparseNode(element: any, properties: any, children: any) {
const el = document.createElement(element) as HTMLElement;
// here it is possible to set style...
// el["style"]["color"] = "red";
Object.keys(nonNull(properties, {})).forEach(key => {
if(key === 'style') {
Object.keys(nonNull(properties[key], {})).forEach(styleKey => {
console.log(element + "." + key + "." + styleKey + " = " + properties[key][styleKey]);
// here it is not possible.......
el[key][styleKey] = properties[key][styleKey];
el["style"]["color"] = "red";
});
} else {
el[key] = properties[key];
}
})
DOMparseChildren(children).forEach((child: any) => {
el.appendChild(child);
});
return el;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.