我的渲染功能为数据中的每个圆返回未定义。
我的圈子数量不定,这就是为什么我需要映射所有圈子的原因。
这是调用render函数的正确方法吗?
如何才能使圆正确返回?
JS
const d = data;
document.getElementById("gElement").innerHTML = `
${d.g.map((entry)=> {
console.log(entry);
return `
<g class="${entry.class}" id="${entry.id}">
<polygon
$points ="${entry.polygon.points}">
</polygon>
${render(entry.circle)}
</g>`
}).join('')}`
function render(circ){
`${circ.map((entry) =>{
return`
<circle
cx = "${entry.cx}"
cy = "${entry.cy}"
r = "${entry.r}"
fill = "${entry.fill}">
</circle>`
}).join('')}`
}
data.json
{
"id": "gElement",
"g": [
{
"class": "polygon",
"id": "elements100",
"polygon": {
"points": "337,212.00000000000006,352.99999999999994,150,433.99999999999994,147.00000000000006,431,206.00000000000006"
},
"circle": [
{
"cx": "337",
"cy": "212.00000000000006",
"r": "2",
"fill": "none"
},
{
"cx": "352.99999999999994",
"cy": "150",
"r": "2",
"fill": "none"
},
{
"cx": "433.99999999999994",
"cy": "147.00000000000006",
"r": "2",
"fill": "none"
},
{
"cx": "431",
"cy": "206.00000000000006",
"r": "2",
"fill": "none"
}
]
}
]
}
答案 0 :(得分:1)
您不能在彼此之间嵌套模板文字,因为反引号会相互干扰。最好的选择是将d.g.map((entry)=> { ... })
抽象到一个单独的函数中,然后在模板文字中调用该函数。
此外,在您的render()
函数中,您没有返回联接的数组。它将返回undefined
,并且您的圈子将永远不会注入HTML。以下脚本应该起作用:
document.getElementById("gElement").innerHTML = getParsedHtml(d);
function getParsedHtml(data) {
return data.g.map(entry => {
return `
<g class="${entry.class}" id="${entry.id}">
<polygon
points ="${entry.polygon.points}">
</polygon>
${render(entry.circle)}
</g>`;
}).join('');
}
function render(circ) {
return circ.map(entry => {
return `
<circle
cx="${entry.cx}"
cy="${entry.cy}"
r="${entry.r}"
fill="${entry.fill}">
</circle>`;
}).join('');
}
我注意到您在多边形的$
属性中有一个points
前缀:我想那是一个错字?
请参见下面的概念验证示例:
const d = {
"id": "gElement",
"g": [{
"class": "polygon",
"id": "elements100",
"polygon": {
"points": "337,212.00000000000006,352.99999999999994,150,433.99999999999994,147.00000000000006,431,206.00000000000006"
},
"circle": [{
"cx": "337",
"cy": "212.00000000000006",
"r": "2",
"fill": "none"
},
{
"cx": "352.99999999999994",
"cy": "150",
"r": "2",
"fill": "none"
},
{
"cx": "433.99999999999994",
"cy": "147.00000000000006",
"r": "2",
"fill": "none"
},
{
"cx": "431",
"cy": "206.00000000000006",
"r": "2",
"fill": "none"
}
]
}]
};
document.getElementById("gElement").innerHTML = getParsedHtml(d);
function getParsedHtml(data) {
return data.g.map(entry => {
return `
<g class="${entry.class}" id="${entry.id}">
<polygon
points ="${entry.polygon.points}">
</polygon>
${render(entry.circle)}
</g>`;
}).join('');
}
function render(circ) {
return circ.map(entry => {
return `
<circle
cx="${entry.cx}"
cy="${entry.cy}"
r="${entry.r}"
fill="${entry.fill}">
</circle>`;
}).join('');
}
svg {
border: 1px solid #000;
width: 250px;
height: 250px;
}
polygon {
fill: grey;
}
circle {
fill: steelblue;
}
<svg viewBox="0 0 500 500">
<g id="gElement"></g>
</svg>