javascript - 如何使用JSX 中的组件?
问题描述
以下在 DOM 树中<Comment>Foo</Comment>
生成<!--[object Object]-->
注释节点。
如何使用它才能生产<!--Foo-->
?
<script>
import { Comment } from 'vue'
export default {
render() {
return <Comment>Foo</Comment>
},
}
</script>
解决方案
您必须创建一个包装器组件来插入文本作为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>
}
}
推荐阅读
- vb.net - vb.net 中的 XML 结构和写入 XML:输出始终为空白
- javascript - Python 访问 Menards 网站上的特定元素
- mysql - MYSQL - 根据另一个表中的条件对一个表中的行的值求和
- flutter - 适用于 Android 和 iOS 上的前台任务的 Flutter 插件
- python - 使用带有 Seaborn 的箱线图搞砸了地块
- csv - 使用谷歌应用脚本导入 csv
- ansible - Ansible 无法导入 Hetzner hcloud Python 库
- javascript - 传单 - 无效的 LatLng 对象:(未定义,-0.3783868407297,43.304121626953)
- reactjs - react-router-v6 访问一个url参数
- javascript - 正则表达式删除具有已知开始和结束模式的子字符串,中间有多个单词