You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React函数改造:将返回值从字符串改为布尔值的技术问询

改造背景色适配文本颜色函数:返回布尔值替代字符串

一、函数改造步骤

因lint限制无法导入UI库的颜色变量,我们将原函数改为仅保留背景色深浅判断逻辑,返回布尔值:

export const getIsLightBackground = (color: string): boolean => {
  let r, g, b;
  const clonedColor = color;

  // 处理RGB/RGBA格式
  if (clonedColor.match(/^rgb/)) {
    const matchResult = clonedColor.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);
    if (matchResult) {
      r = parseInt(matchResult[1], 10);
      g = parseInt(matchResult[2], 10);
      b = parseInt(matchResult[3], 10);
    }
  } else {
    // 处理十六进制格式(支持3位或6位)
    const hexValue = +('0x' + clonedColor.slice(1).replace(clonedColor.length < 5 && /./g, '$&$&'));
    r = hexValue >> 16;
    g = (hexValue >> 8) & 255;
    b = hexValue & 255;
  }

  // 计算HSP值判断背景深浅
  const hsp = Math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b));
  // 背景偏亮返回true,偏暗返回false
  return hsp > 127.5;
};

关键改动:

  • 移除@vetera-sky/shared/ui的颜色变量导入
  • 返回值类型从string改为boolean,直接返回背景深浅的判断结果
  • 修复原代码中clonedColor初始未赋值的bug,确保RGB格式判断逻辑生效
  • 增加RGB匹配结果的空值判断,避免类型错误
  • 函数名改为语义化的getIsLightBackground,明确返回值含义

二、在UI/业务组件中使用

在需要适配文本颜色的组件里,导入颜色变量和改造后的函数,根据布尔值选择对应颜色:

import { textEmphasis, textOnInteractive } from '@vetera-sky/shared/ui';
import { getIsLightBackground } from './path-to-your-function';

const YourComponent = ({ backgroundColor }: { backgroundColor: string }) => {
  const isLightBackground = getIsLightBackground(backgroundColor);
  // 根据背景深浅切换文本颜色
  const textColor = isLightBackground ? textEmphasis : textOnInteractive;

  return (
    <div style={{ backgroundColor, color: textColor }}>
      自适应颜色的文本内容
    </div>
  );
};

export default YourComponent;

逻辑说明:

  • 背景偏亮(isLightBackground为true):使用深色文本textEmphasis
  • 背景偏暗(isLightBackground为false):使用浅色文本textOnInteractive

内容的提问来源于stack exchange,提问作者triple-D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 04:45:45