Vue中注册函数式组件并使用JSX,需设functional: true、无响应式数据、无this,render函数接收h和context参数;通过components选项局部注册,JSX中用三元/Map替代v-if/v-for,事件用on:或onClick。

函数式组件的本质要求
函数式组件必须满足:
• 没有响应式数据(无 data、computed、watch)
• 没有实例上下文(不可访问 this)
• 必须设置 functional: true
• 渲染逻辑写在 render 函数中,接收两个参数:h(即 createElement)和 context(含 props、slots、scopedSlots、attrs 等)
正确注册方式(局部注册示例)
在父组件中局部注册一个函数式 JSX 组件:
// MyFunctionalComp.jsx(或 .js)
export default {<br>
name: 'MyFunctionalComp',<br>
functional: true,<br>
props: { title: String },<br>
render(h, context) {<br>
const { props, slots, scopedSlots } = context;<br>
return h('div', { class: 'func-comp' }, [<br>
h('h2', props.title),<br>
slots().default,<br>
scopedSlots.default && scopedSlots.default({ msg: '来自函数式组件' })<br>
])<br>
}<br>
}
// Parent.vue(局部注册)
import MyFunctionalComp from './MyFunctionalComp.jsx'<br>
export default {<br>
components: { MyFunctionalComp }<br>
}
使用:<myfunctionalcomp title="Hello"><p>默认插槽</p>
<p><span>立即学习</span>“<a href="https://pan.quark.cn/s/cb6835dc7db1" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">前端免费学习笔记(深入)</a>”;</p></myfunctionalcomp>
JSX 写法要点(非 template)
JSX 中不能写 v-if、v-for 等指令,要转为 JS 逻辑:
-
v-if → 用三元表达式或逻辑与:
{ props.show ? h('span', '显示') : null } -
v-for → 用
map:{ props.list.map(item => h('li', item.name)) } -
事件绑定 →
on: { click: () => emit('click') }或简写onClick={...}(注意:Vue 2 JSX 中推荐用onXxx形式,如onClick) -
class / style → 直接写对象:
class={{ active: props.isActive }},style={{ color: props.color }}
注意事项
• Vue 2 需安装 Babel 插件:@vue/babel-preset-jsx,并在 .babelrc 中配置
• functional: true 是硬性要求,漏写就不是函数式组件,context 也不会传入
• 不可使用 this,所有数据都从 context.props、context.slots() 等获取
• 插槽访问统一走 context.slots()(返回对象)和 context.scopedSlots(函数对象)


















