You need to enable JavaScript to run this app. React中.map返回值匹配指定字符串时,如何渲染带跳转按钮的表格
优惠活动
大模型
产品
解决方案
定价
更多

React中.map返回值匹配指定字符串时,如何渲染带跳转按钮的表格

实现方案

核心逻辑是遍历每个myguids.guid时,判断其是否匹配指定前缀字符串,匹配则渲染为超链接实现跳转,否则正常渲染内容。同时修正原代码缺少<table>标签包裹的结构问题,字符串匹配统一转小写处理避免大小写不一致导致匹配失败。

完整修改后代码

import React, { useContext } from 'react';
import { Button } from 'antd'; // 按需替换为你实际使用的Button组件引入路径
import { AppContext } from './你的AppContext实际路径'; // 替换为真实的AppContext引入路径

// 提前提取匹配前缀为常量,后续修改更方便
const TARGET_PREFIX = 'http://linkedbuildingdata.net/ifc/resources20201208_005325/'

const QueryTable = ({guidList}) => {
    const { context, setContext } = useContext(AppContext); 

    // 封装内容渲染判断逻辑
    const renderGuid = (guid) => {
        // 统一转小写判断,避免大小写问题导致匹配失效
        if(guid.toLowerCase().startsWith(TARGET_PREFIX.toLowerCase())){
            // 匹配到前缀则渲染为超链接
            return <a href={guid} target="_blank" rel="noopener noreferrer">{guid}</a>
        }
        // 未匹配则正常渲染按钮
        return <Button>{guid}</Button>
    }

    return (
        <div>
            QueryTable 
            <table>
                <tbody>
                {guidList?.length > 0 && guidList.map((myguids, key) => (
                    <tr key={key}>
                        <td>property: {renderGuid(myguids.guid)}</td>
                    </tr>
                ))}
                </tbody>
            </table>
        </div>
        )
}

export default QueryTable

代码说明

  • 用startsWith方法判断字符串前缀,比全量匹配更精准
  • 新增target="_blank"实现新页面跳转,rel="noopener noreferrer"符合前端安全规范
  • 用可选链guidList?.length简化非空判断,写法更简洁
  • 删掉了不必要的React.Fragment和数组包裹,简化返回结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 02:54:06