【发布时间】:2020-04-08 05:59:10
【问题描述】:
下面有一些 JSX 在 firstComment 元素之前注入到 DOM 中。
里面有几个简单地返回 svgs 的函数。当浏览器运行thumbsUp()和thumbsDown()函数时,它们会显示为[object Object][object Object]。
如何在不直接用 svg 替换函数的情况下使此代码正常工作?如果需要,我愿意使用与 insertAdjacentHTML 不同的方法。
const postComment = (inputValue) =>
{
const d1 = document.getElementById('firstComment')
d1.insertAdjacentHTML('beforebegin',
`
<div>
<div class="comment-avatar"></div>
<div class="comment-container">
<h5 class="commentorName">Guest</h5>
<div class="dateOfComment">Just Now</div>
<p class="comment">${inputValue}</p>
<div class="thumbs">
<span class="thumbsUpIcon">
${thumbsUp(16)}
</span>
<span class="thumbsDownIcon">
${thumbsDown(16)}
</span>
</div>
<p class="replyText">REPLY</p>
</div>
</div>
`
)
}
功能
const thumbsUp = (width) => {
return (
<svg width={width} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M198 448h172c15.7 0 28.6-9.6 34.2-23.4l57.1-135.4c1.7-4.4 2.6-9 2.6-14v-38.6c0-21.1-17-44.6-37.8-44.6H306.9l18-81.5.6-6c0-7.9-3.2-15.1-8.3-20.3L297 64 171 191.3c-6.8 6.9-11 16.5-11 27.1v192c0 21.1 17.2 37.6 38 37.6zM48 224h64v224H48z"/></svg>
)
}
const thumbsDown = (width) => {
return (
<svg width={width} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M314 64H142c-15.7 0-28.6 9.6-34.2 23.4L50.6 222.8c-1.7 4.4-2.6 9-2.6 14v38.6c0 21.1 17 44.6 37.8 44.6h119.3l-18 81.5-.6 6c0 7.9 3.2 15.1 8.3 20.3l20 20.1L341 320.7c6.8-6.9 11-16.5 11-27.1v-192c0-21.1-17.2-37.6-38-37.6zM400 64h64v224h-64z"/></svg>
)
}
【问题讨论】:
-
您能否在您的问题中也发布
thumbsUp函数和thumbsDown函数。 -
当然。但这就像我说的那样。他们所做的就是返回 svg。我在应用程序的许多地方都使用了它们,因此该功能可以按预期工作。
-
如果你把返回的 SVG 代码变成一个字符串,这样行吗?例如:
const thumbsUp = (width) => { return '<svg></svg>'}. -
@JustinFeakes 这行得通,但是在我要导入该函数的所有其他区域中破坏了我的代码。
-
嗯,您在哪里调用 ${thumbsUp(16)},您可以将其转换为字符串并保持函数不变吗?例如
${thumbsUp(16).toString()}
标签: javascript reactjs components jsx react-component