[英]cant set style attribute value javascript / typescript
I am trying to set the style for an element from a supplied object.我正在尝试为提供的 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 console.log
确实记录了正确的 output: h1.style.color = red
So why doesn't it apply my style right below the console.log
??那么为什么它不在
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 the最终目标是取代
el["style"]["color"] = "red";
with和
el[key][styleKey] = properties[key][styleKey];
The line线
el[key] = properties[key];
is overwriting all the styles that were set in the properties[key]
loop.正在覆盖在
properties[key]
循环中设置的所有 styles。 You should put that in an else
block so it's only done for non-style
properties.你应该把它放在一个
else
块中,所以它只适用于non-style
属性。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.