[英]How to use <Comment> component in JSX?
The following <Comment>Foo</Comment>
produces <!--[object Object]-->
comment node in the DOM tree.下面的
<Comment>Foo</Comment>
在 DOM 树中生成<!--[object Object]-->
注释节点。
How to use it so that it can produce <!--Foo-->
?如何使用它才能产生
<!--Foo-->
?
<script>
import { Comment } from 'vue'
export default {
render() { 👇
return <Comment>Foo</Comment>
},
}
</script>
You'd have to create a wrapper component to insert text as a child of Comment
.您必须创建一个包装器组件来插入文本作为
Comment
的子级。 The following MyComment
functional component flattens the text nodes from its default slot, and passes the result as the Comment
child:以下
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()))
Then use it in your JSX:然后在你的 JSX 中使用它:
import { MyComment } from '@/components/MyComment'
export default {
render() {
return <div>
<span>foo bar</span>
<MyComment>This is a comment</MyComment>
</div>
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.