You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Vue.js中从函数渲染JSX的技术问询

Vue.js中用函数渲染JSX+插槽的实操指南

嘿,我刚入门Vue的时候也试过直接照搬React那套写JSX,结果踩了好几个坑!别担心,我来一步步给你讲清楚怎么弄~

首先得明确:Vue里的JSX写法和React确实有不少差异,尤其是插槽这块,不能直接用props.children,得用Vue自己的插槽机制。先从基础准备开始说:

1. 先确保项目支持JSX

如果你的项目还没配置JSX支持,得先搞定这个:

  • Vue3 + Vite:安装@vitejs/plugin-vue-jsx,然后在vite.config.js里添加插件配置:
    import { defineConfig } from 'vite'
    import vue from '@vitejs/plugin-vue'
    import vueJsx from '@vitejs/plugin-vue-jsx'
    
    export default defineConfig({
      plugins: [vue(), vueJsx()]
    })
    
  • Vue3 + Vue CLI:默认已经支持JSX,不用额外配置;老项目的话安装@vue/babel-plugin-jsx并在babel配置里启用即可。
  • Vue2:安装@vue/babel-preset-jsx,然后在.babelrc里配置对应的预设。

2. 用函数渲染JSX的正确姿势

在Vue里,你不能直接在模板里调用函数返回JSX,得把JSX写在组件的render函数里,或者Vue3的setup返回函数里。举个Vue3的例子:

子组件(用JSX定义)

<script lang="jsx">
import { defineComponent } from 'vue'

export default defineComponent({
  props: {
    cardTitle: String
  },
  setup(props, { slots }) {
    // 这里的返回值就是渲染函数,直接返回JSX结构
    return () => (
      <div class="card-container">
        <h2>{props.cardTitle}</h2>
        {/* 渲染默认插槽内容 */}
        {slots.default?.()}
        {/* 渲染具名插槽(比如footer) */}
        <div class="card-footer">
          {slots.footer?.()}
        </div>
      </div>
    )
  }
})
</script>

父组件调用(用模板传插槽)

<template>
  <CardComponent cardTitle="我的JSX卡片">
    <!-- 默认插槽内容 -->
    <p>这是卡片的主体内容,用默认插槽传递</p>
    <!-- 具名插槽footer -->
    <template #footer>
      <button>点击查看详情</button>
    </template>
  </CardComponent>
</template>

<script setup>
import CardComponent from './CardComponent.vue'
</script>

如果是Vue2的话,写法稍微不同,用this.$slots来访问插槽:

<script lang="jsx">
export default {
  props: {
    cardTitle: String
  },
  render() {
    return (
      <div class="card-container">
        <h2>{this.cardTitle}</h2>
        {/* 默认插槽 */}
        {this.$slots.default}
        {/* 具名插槽footer */}
        <div class="card-footer">
          {this.$slots.footer}
        </div>
      </div>
    )
  }
}
</script>

3. 你之前失败的可能原因

你说用React式语法没成功,大概率是这几点:

  • 没配置JSX支持,导致代码无法编译
  • 用了React的props.children来拿插槽内容,Vue里得用slots(Vue3)或this.$slots(Vue2)
  • 直接在模板里写JSX代码,Vue模板不支持直接写JSX,必须放在render函数/setup返回函数里

小提示

  • Vue3的JSX里,事件绑定和React一样用驼峰式(比如onClick),class用class或者className都可以
  • 如果插槽可能为空,记得用?.()来避免报错(Vue3里),Vue2里直接访问this.$slots.xxx就行,空的话会渲染null

如果还有细节搞不懂,随时问哦!

内容的提问来源于stack exchange,提问作者jaysig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:36:00