【发布时间】:2020-06-24 20:48:49
【问题描述】:
我正在尝试为提供的对象中的元素设置样式。像这样:
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);
}
用法,它应该有助于以下场景:
document.body.appendChild(<div style={{color: 'red'}}></div>)
console.log 确实记录了正确的输出:h1.style.color = red
那么为什么它不在console.log 正下方应用我的样式呢??
我没有收到任何错误。这使得调试变得更加困难:(
如果需要更多上下文,请告诉我!
最终目标是替换el["style"]["color"] = "red";
与el[key][styleKey] = properties[key][styleKey];
【问题讨论】:
-
你说的不符合你的风格是什么意思?您是否将元素附加到正文?
-
您应用的样式与您在函数顶部应用的样式相同。你怎么知道它不起作用?
-
@hev1 是的,它确实应用了我的元素,还有更多代码,但我忽略了。
-
@Barmar 当然,我尝试将每一行分开 :)
-
请发帖minimal reproducible example。您可以使用Stack Snippet 使其可执行。
标签: javascript css typescript object jsx