首页 > 解决方案 > 如何使用JSX 中的组件?

问题描述

以下在 DOM 树中<Comment>Foo</Comment>生成<!--[object Object]-->注释节点。

如何使用它才能生产<!--Foo-->

<script>
  import { Comment } from 'vue'

  export default {
    render() {        
      return <Comment>Foo</Comment>
    },
  }
</script>

标签: javascriptvue.jsjsxvuejs3

解决方案


您必须创建一个包装器组件来插入文本作为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>
  }
}

推荐阅读