Skip to content

domTarget

源码

ts
import type { MutableRefObject } from 'react'
import { isFunction } from './index'
import isBrowser from './isBrowser'

type TargetValue<T> = T | undefined | null

type TargetType = HTMLElement | Element | Window | Document

export type BasicTarget<T extends TargetType = Element> =
  | (() => TargetValue<T>)
  | TargetValue<T>
  | MutableRefObject<TargetValue<T>>

//
export function getTargetElement<T extends TargetType>(target: BasicTarget<T>, defaultElement?: T) {
  // 判断是不是浏览器环境
  if (!isBrowser) {
    return undefined
  }

  // 如果没有传入target,就返回默认的dom
  if (!target) {
    return defaultElement
  }

  let targetElement: TargetValue<T>

  // 如果是函数,就执行函数
  if (isFunction(target)) {
    targetElement = target()
    // 如果是ref,就获取ref.current
  } else if ('current' in target) {
    targetElement = target.current
  } else {
    // 否则就是dom
    targetElement = target
  }

  return targetElement
}

如有转载或 CV 的请标注本站原文地址