【问题标题】:How to use <Comment> component in JSX?如何在 JSX 中使用 <Comment> 组件?
【发布时间】:2021-04-22 00:46:58
【问题描述】:

以下&lt;Comment&gt;Foo&lt;/Comment&gt; 在DOM 树中生成&lt;!--[object Object]--&gt; 注释节点。

如何使用它才能产生&lt;!--Foo--&gt;

<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>
      }
    }
    

    【讨论】:

    • 工作,但感觉有点迂回。
    • 不幸的是,我不相信还有其他方法。
    猜你喜欢
    • 2021-03-09
    • 2019-05-17
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2019-07-04
    • 2020-05-05
    • 2017-06-25
    • 1970-01-01
    相关资源
    最近更新 更多