视图构建

h()

创建虚拟视图节点,是 JSX 编译的底层实现。

类型定义

ts
declare function h<T extends ViewDescriptor>(
  type: T,
  propsOrChildren?: AnyProps | RenderChildren,
  children?: RenderChildren
): InferView<T>

参数

参数类型说明
typeViewDescriptor标签名、组件或 ViewBuilder
propsOrChildrenAnyProps | RenderChildren属性或子节点
childrenRenderChildren子节点

返回值

类型说明
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返回视图的渲染函数
locationCodeLocation可选的代码位置信息

返回值

类型说明
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()

合并多个属性对象,处理 classstyle 的特殊合并逻辑。

类型定义

ts
declare function mergeProps(p1: AnyProps, p2: AnyProps): AnyProps

参数

参数类型说明
p1AnyProps第一个属性对象
p2AnyProps第二个属性对象

返回值

类型说明
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
}
属性类型说明
childrenRenderChildren子节点

示例

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
}
属性类型说明
isViewDescriptor | undefined | null | false要渲染的组件、标签或视图构建器
keyunknown可选的缓存 key
memoboolean | number可选的缓存策略
childrenRenderChildren子节点

示例

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
}
属性类型说明
textstring注释文本

示例

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
}
属性类型说明
textstring | number文本内容

示例

tsx
import { PlainText } from 'vitarx'

function App() {
  return <PlainText text="Hello World" />
}