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

React TypeScript新手求助:控制SVG图标显示的hideSvgIcon方法失效

问题描述

我是React TypeScript新手,希望在界面中隐藏指定SVG图标,仅当aggregationCode为2、3、4、5时显示。我编写了hideSvgIcon方法来实现这个逻辑,但该方法未生效。以下是我的代码:

const hideSvgIcon = (aggregationCode: number) => {
    const listeAggregationTooltip = [2, 3, 4, 5]
    return listeAggregationTooltip.includes(aggregationCode)
}

return (
    <tr>
        <td className="name">Critère d'agrégation</td>
        <td className="value column-2">
            {aggregationDomain.map(codedValue => 
                <>
                    <label id="label"  data-tooltip={getTooltipName(codedValue.name)} className={!config?.aggregationEnabled.includes(codedValue.code) ? 'text-gray' : ''}>
                        <input type="radio" name="AggregationSelection" value={codedValue.code} checked={props.reportConfig.aggregation === codedValue.code} onChange={updateAggregation} disabled={!config?.aggregationEnabled.includes(codedValue.code)} />
                        {codedValue.name} 
                    </label>  
                    {hideSvgIcon(codedValue.code) ? (
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width='13' height='13'>
                            <path d="M256 512c141.4 0 256-114.6 256-256S397.4 0 256 0S0 114.6 0 256S114.6 512 256 512zM216 336h24V272H216 192V224h24 48 24v24 88h8 24v48H296 216 192V336h24zm72-144H224V128h64v64z"/>
                        </svg>
                    ) : <></>}
                </>               
            )}
        </td>
    </tr>
)

排查与解决方法

  • 检查codedValue.code的类型:Array.includes()对类型严格匹配,如果codedValue.code实际是字符串类型(比如"2"而非2),数组里的数字2和它不匹配,会返回false。解决办法:要么把数组改成字符串数组["2", "3", "4", "5"],要么在调用方法时把参数转成数字hideSvgIcon(Number(codedValue.code))。
  • 添加调试日志确认参数:在hideSvgIcon方法里打印传入的参数和判断结果,确认实际值是否符合预期:
    const hideSvgIcon = (aggregationCode: number) => {
        const listeAggregationTooltip = [2, 3, 4, 5]
        console.log("当前code值:", aggregationCode, "匹配结果:", listeAggregationTooltip.includes(aggregationCode))
        return listeAggregationTooltip.includes(aggregationCode)
    }
    
    查看控制台输出,就能知道是参数不对还是逻辑问题。
  • 简化判断逻辑直接测试:暂时把方法调用替换成直接的数组判断,排除函数本身的问题:
    {[2,3,4,5].includes(codedValue.code) ? <svg>...</svg> : <></>}
    
    如果这样能生效,说明之前的函数调用可能存在参数传递错误;如果还是不生效,继续排查参数类型。
  • 检查CSS是否干扰:确认没有全局样式或父元素的CSS规则(比如display: none、opacity: 0)意外隐藏了SVG图标。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:25:30