【问题标题】:How to use <Comment> component in JSX?如何在 JSX 中使用 <Comment> 组件?
【发布时间】:2021-04-22 00:46:58
【问题描述】:
以下<Comment>Foo</Comment> 在DOM 树中生成<!--[object Object]--> 注释节点。
如何使用它才能产生<!--Foo-->?
<script>
import { Comment } from 'vue'
export default {
render() { ????
return <Comment>Foo</Comment>
},
}
</script>
【问题讨论】:
标签:
javascript
vue.js
jsx
vuejs3
【解决方案1】:
您必须创建一个包装器组件来插入文本作为Comment 的子项。以下MyComment 功能组件将文本节点从其默认槽中展平,并将结果作为Comment 子节点传递:
// @/components/MyComment.js
import { Comment, h } from 'vue'
const getText = node => {
if (typeof node === 'string') return node
if (Array.isArray(node)) {
return node.map(getText).join('')
}
if (node.children) {
return getText(node.children)
}
}
export const MyComment = (props, {slots}) => h(Comment, slots.default && getText(slots.default()))
然后在你的 JSX 中使用它:
import { MyComment } from '@/components/MyComment'
export default {
render() {
return <div>
<span>foo bar</span>
<MyComment>This is a comment</MyComment>
</div>
}
}