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

ReactJS+TypeScript设计系统组件类型传递与返回问题求助

问题分析与修复方案

你的代码存在几个核心问题,导致类型传递和组件渲染不符合预期,以下是逐一修复的方案:

核心问题点

  • 拼写错误:getTilte应为getTitle,函数名错误会导致逻辑无法正常执行
  • getTitle函数未接收linguage参数,无法根据传入的语言值判断返回内容
  • 辅助函数返回时直接返回函数引用(如return getTitlePt),而非调用后生成的JSX元素,需要改为return getTitlePt()
  • 辅助函数中错误传递linguage属性(比如getTitleEn里错误传入pt-BR,getTitleEs传入空字符串),违反了TitleProps的类型约束
  • 主Title组件未使用传入的linguage参数,始终渲染固定的葡萄牙语内容

修复后的完整代码

import React from "react";
import './title.css'

export type TitleProps = {
  linguage: 'pt-BR' | 'es-CL' | 'en-US'
}

// 根据语言返回对应标题的辅助函数
const getTitleContent = (linguage: TitleProps['linguage']) => {
  switch(linguage) {
    case 'pt-BR':
      return {
        text: 'Gerenciamos sua TI com excelência',
        className: 'storybook-title-portugues'
      };
    case 'en-US':
      return {
        text: 'We manage your IT with excellence',
        className: 'storybook-title--english'
      };
    case 'es-CL':
      return {
        text: 'Gestionamos tu TI con excelencia',
        className: 'storybook-title--espanol'
      };
  }
}

export const Title = ({ linguage }: TitleProps) => {
  const { text, className } = getTitleContent(linguage);
  // 若需给h1传递linguage属性,可添加`linguage={linguage}`到props中
  return (
    <h1 className={className}>
      {text}
    </h1>
  );
}

关键修改说明

  1. 简化逻辑:将多个独立的标题函数合并为getTitleContent,通过switch判断语言返回对应的文本和类名,避免重复代码
  2. 类型安全:严格遵循TitleProps的linguage类型约束,确保所有分支的返回值符合要求
  3. 正确渲染:主Title组件根据传入的linguage参数动态获取内容,而非固定返回同一结果
  4. 冗余消除:移除了不必要的linguage属性传递(除非你的CSS或其他逻辑需要,可自行添加)

如果需要保留原有的独立函数写法,也可以修改为以下版本:

import React from "react";
import './title.css'

export type TitleProps = {
  linguage: 'pt-BR' | 'es-CL' | 'en-US'
}

const getTitlePt = () => (
  <h1 className="storybook-title-portugues">
    Gerenciamos sua TI com excelência
  </h1>
);
const getTitleEn = () => (
  <h1 className="storybook-title--english">
    We manage your IT with excellence
  </h1>
);
const getTitleEs = () => (
  <h1 className="storybook-title--espanol">
    Gestionamos tu TI con excelencia
  </h1>
);
// 修正函数名并接收参数
const getTitle = (linguage: TitleProps['linguage']) => {
  if (linguage === 'pt-BR') {
    return getTitlePt(); // 调用函数返回JSX
  } else if (linguage === 'en-US') {
    return getTitleEn();
  } else {
    return getTitleEs();
  }
}

export const Title = ({ linguage }: TitleProps) => {
  return getTitle(linguage); // 根据语言返回对应组件
}

内容的提问来源于stack exchange,提问作者Samuel Máximo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:54:50