如何在React的JSX模板字符串中内联调用capitalize函数?
在JSX中内联调用首字母大写函数的正确方式
你原来的代码里犯了个小错误:把capitalize当成字符串的内置属性来调用(?.timer_type.capitalize),但它是你定义的独立函数,得用函数调用的方式来使用。
正确的做法是,把timerTypes.find返回结果里的timer_type作为参数传给capitalize函数,同时要处理find可能找不到匹配项的情况(避免传入undefined导致报错)。
修改后的关键代码片段
<strong> {`${ capitalize(timerTypes.find((type) => type.id === history.timer_type)?.timer_type || '') } for ${toTime(history.duration_seconds)}`} </strong>
更清晰的写法(拆分逻辑)
如果觉得内联代码太拥挤,也可以把查找和格式化逻辑抽出来,让代码可读性更强:
{timerHistory && timerHistory.map((history, index) => { const matchedType = timerTypes.find((type) => type.id === history.timer_type); // 找不到匹配项时显示空字符串,避免报错 const formattedTypeName = matchedType ? capitalize(matchedType.timer_type) : ''; return ( <Box key={index}> <strong> {`${formattedTypeName} for ${toTime(history.duration_seconds)}`} </strong> {` on a ${Math.round(history.goal_seconds / 60)} minute timer ${age(history.created_at)}`} </Box> ); })}
本质上,JSX内联调用函数就是直接在花括号里写函数名(参数)的形式,只要确保传入的参数合法(比如用|| ''兜底空值)就可以正常运行。
内容的提问来源于stack exchange,提问作者Fighithebird
相关产品推荐
相关产品推荐

