You need to enable JavaScript to run this app. React基于if条件判断返回对应网页布局失效,如何正确实现?
优惠活动
大模型
产品
解决方案
定价
更多

React基于if条件判断返回对应网页布局失效,如何正确实现?

问题修复方案

核心问题说明

你当前的实现存在3个可优化/错误点:

  • personSafety目前被定义为字符串模板,不是可渲染的React函数组件,无法通过<personSafety />的方式调用渲染
  • React自定义组件必须首字母大写,否则会被识别为原生HTML标签,无法正常解析
  • 后续要扩展到30种条件判断时,大量堆叠if判断会非常难维护,更推荐用映射表的方案实现,后续新增条件只需要加一行映射关系即可

调整后的代码实现

1. 修改PersonSafety.js代码

import React from 'react';
import { Typography } from '@material-ui/core';

// 首字母大写,改为标准React函数组件
export const PersonSafety = () => {
  return (
    <Typography gutterBottom>
      Person is not very safe
    </Typography>
  );
};

2. 修改TagContent组件代码

import React from 'react';
import { PersonSafety } from './modals/PersonSafety';
// 后续其他场景的组件都可以在此处引入
// import { SceneA } from './modals/SceneA';
// import { SceneB } from './modals/SceneB';

// 建立tagText和对应组件的映射表
const tagComponentMap = {
  'Person is unsafe': PersonSafety,
  // 后续新增30种条件只需要在这里加对应映射即可,不需要编写大量if判断
  // 'tag文本A': SceneA,
  // 'tag文本B': SceneB,
};

export default function TagContent(props) {
  // 从映射表匹配对应组件,无匹配时可返回null或者默认占位内容
  const RenderComponent = tagComponentMap[props.tagText];
  return RenderComponent ? <RenderComponent /> : null;
}

内容的提问来源于stack exchange,提问作者Jon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 18:54:03