视图构建
h()
创建虚拟视图节点,是 JSX 编译的底层实现。
类型定义
ts
declare function h<T extends ViewDescriptor>(
type: T,
propsOrChildren?: AnyProps | RenderChildren,
children?: RenderChildren
): InferView<T>参数
| 参数 | 类型 | 说明 |
|---|---|---|
type | ViewDescriptor | 标签名、组件或 ViewBuilder |
propsOrChildren | AnyProps | RenderChildren | 属性或子节点 |
children | RenderChildren | 子节点 |
返回值
| 类型 | 说明 |
|---|---|
InferView<T> | 视图对象 |
示例
tsx
import { h } from 'vitarx'
// 创建元素
const el = h('div', { class: 'container' }, 'Hello')
// 创建组件
const comp = h(MyComponent, { prop: 'value' })
// 嵌套子节点
const nested = h('div', null, [h('span', null, 'Hello'), h('span', null, 'World')])dynamic()
动态渲染视图,支持运行时响应式切换。
类型定义
ts
declare function dynamic<T>(build: () => T, location?: CodeLocation): DynamicView<T>参数
| 参数 | 类型 | 说明 |
|---|---|---|
build | () => T | 返回视图的渲染函数 |
location | CodeLocation | 可选的代码位置信息 |
返回值
| 类型 | 说明 |
|---|---|
DynamicView<T> | 动态视图对象 |
示例
tsx
import { dynamic, ref } from 'vitarx'
function App() {
const show = ref(true)
return dynamic(() => {
return show.value ? <div>显示</div> : <div>隐藏</div>
})
}参考:dynamic 详解
mergeProps()
合并多个属性对象,处理 class 和 style 的特殊合并逻辑。
类型定义
ts
declare function mergeProps(p1: AnyProps, p2: AnyProps): AnyProps参数
| 参数 | 类型 | 说明 |
|---|---|---|
p1 | AnyProps | 第一个属性对象 |
p2 | AnyProps | 第二个属性对象 |
返回值
| 类型 | 说明 |
|---|---|
AnyProps | 合并后的属性对象 |
示例
ts
import { mergeProps } from 'vitarx'
const merged = mergeProps({ class: 'a', id: 'test' }, { class: 'b', style: 'color: red' })
// { class: 'a b', id: 'test', style: 'color: red' }Fragment
片段容器,不渲染额外 DOM 元素,用于返回多个根节点。
Props
ts
interface FragmentProps {
children?: RenderChildren
}| 属性 | 类型 | 说明 |
|---|---|---|
children | RenderChildren | 子节点 |
示例
tsx
import { Fragment } from 'vitarx'
function MultiRoot() {
return (
<Fragment>
<div>First</div>
<div>Second</div>
</Fragment>
)
}Dynamic
动态组件渲染器,根据条件渲染不同的组件。
Props
ts
interface DynamicProps {
is: ViewDescriptor | undefined | null | false
key?: unknown
memo?: boolean | number
children?: RenderChildren
[key: string]: any
}| 属性 | 类型 | 说明 |
|---|---|---|
is | ViewDescriptor | undefined | null | false | 要渲染的组件、标签或视图构建器 |
key | unknown | 可选的缓存 key |
memo | boolean | number | 可选的缓存策略 |
children | RenderChildren | 子节点 |
示例
tsx
import { Dynamic, ref } from 'vitarx'
function App() {
const currentComponent = ref(HomeComponent)
return <Dynamic is={currentComponent} />
}参考:Dynamic 详解
Comment
注释节点,渲染为 HTML 注释。
Props
ts
interface CommentProps {
text: string
}| 属性 | 类型 | 说明 |
|---|---|---|
text | string | 注释文本 |
示例
tsx
import { Comment } from 'vitarx'
function App() {
return (
<div>
<Comment text="section start" />
<div>Content</div>
</div>
)
}PlainText
纯文本节点,直接渲染文本内容。
Props
ts
interface PlainTextProps {
text: string | number
}| 属性 | 类型 | 说明 |
|---|---|---|
text | string | number | 文本内容 |
示例
tsx
import { PlainText } from 'vitarx'
function App() {
return <PlainText text="Hello World" />
}