renderElement

预计阅读时间: 3 分钟

渲染 UI 组件元素的工具函数。

renderElement 处理 Video.js React 中 UI 组件的渲染逻辑,包括默认标签渲染、render props、props 合并、ref 组合以及状态驱动的 className 和 style。

示例

基本用法

import { renderElement } from '@videojs/react';

function MyComponent({ playerState }) {
  return renderElement({
    element: 'button',
    className: 'my-button',
    props: {
      type: 'button',
      onClick: () => console.log('clicked'),
    },
    state: playerState,
    defaultClassName: 'vjs-control',
  });
}

配合 Render Props

import { renderElement } from '@videojs/react';

function CustomRenderer({ children, playerState }) {
  return renderElement({
    element: 'div',
    props: {
      role: 'group',
      'aria-label': 'Custom controls',
    },
    render: (props) => (
      <div {...props}>
        {typeof children === 'function'
          ? children(props)
          : children}
      </div>
    ),
    state: playerState,
  });
}

动态 ClassName 和 Style

import { renderElement } from '@videojs/react';

function StateDrivenElement({ playerState, isActive }) {
  return renderElement({
    element: 'div',
    className: (state) => isActive ? 'active' : 'inactive',
    style: (state) => ({
      opacity: isActive ? 1 : 0.5,
      transition: 'opacity 0.2s ease',
    }),
    props: {
      'data-state': playerState.paused ? 'paused' : 'playing',
    },
    state: playerState,
  });
}

API 参考

参数

参数类型默认值说明
elementstring | ReactElement默认 HTML 标签名称
componentPropsobject{}传递给组件的 props
paramsRenderElementParams渲染参数配置

RenderElementParams

参数类型默认值说明
elementstring | ReactElement默认 HTML 标签或自定义元素
classNamestring | ((state: object) => string)CSS 类名或动态类名函数
styleCSSProperties | ((state: object) => CSSProperties)内联样式或动态样式函数
propsobject额外的 props 对象
renderReact.FC | ((props: object) => ReactNode)自定义渲染函数(render prop)
refRefObject | RefCallbackref 对象或回调 ref
stateobject用于驱动动态 className 和 style 的状态对象
defaultClassNamestring默认 CSS 类名

返回值

ReactElement | null

返回渲染后的 React 元素,如果 render 函数返回 null 或 falsy 值则返回 null。

功能特性

Props 合并

renderElement 会自动合并多个来源的 props:

  1. componentProps 传入的默认 props
  2. params.props 传入的额外 props
  3. 自动计算的 props(如 ref、className、style)

Ref 组合

支持多种 ref 组合方式:

  • 单独使用 ref 参数
  • 使用 componentProps.ref
  • 同时使用两者(会依次调用)

状态驱动的样式

classNamestyle 为函数时,会使用 state 参数调用它们:

// 动态 className
className: (state) => state.isActive ? 'active' : 'inactive'

// 动态 style
style: (state) => ({ opacity: state.disabled ? 0.5 : 1 })

参见