All files / react useClassName.ts

100% Statements 8/8
100% Branches 6/6
100% Functions 3/3
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38                                                  5x 5x 5x 4x 24x   4x   1x   5x    
import { DependencyList, useMemo } from 'react'
 
/**
 * 获取类名字符串。
 *
 * @public
 * @param getClassValues 获取类名列表函数
 * @param deps 当依赖变更时重新获取
 * @returns 返回类名字符串
 * @example
 * ```typescript
 * const [mini, setMini] = useState(true)
 * const buttonClassName = useClassName(() => [
 *   'ui-btn',
 *   mini && 'ui-btn_mini',
 * ], [mini])
 * console.log(buttonClassName) // => 'ui-btn ui-btn_mini'
 * setMini(false)
 * console.log(buttonClassName) // => 'ui-btn'
 * ```
 */
export function useClassName(
  getClassValues: () => any[] | undefined,
  deps: DependencyList,
): string | undefined {
  const className = useMemo(() => {
    const classValues = getClassValues()
    if (classValues) {
      const validClassValues = classValues.filter(
        value => typeof value === 'string' && value !== '',
      )
      return validClassValues.length ? validClassValues.join(' ') : undefined
    }
    return undefined
  }, deps)
  return className
}