React.js中如何通过map动态修改以<All.开头的标签名
React循环中动态渲染All命名空间下的组件
我需要在React的map循环里动态修改All.开头的标签名,原代码如下:
{services.map((item) => ( <div className="space-x-[8px] py-[8px] flex "> <div className="flex flex-col text-center relative px-[8px] py-[8px] items-center active:bg-[#f5f5f5] cursor-pointer"> <All.${item} sx={{ fontSize: "40px" }} className="text-[#6B84DD] w-[64px] h-[p64x] text-3xl" /> <span className=" font-merrisans text-[14px] font-semibold"> {item} </span> </div> </div> ))}
我尝试把组件转成字符串拼接的写法,结果页面直接渲染出代码文本,没有渲染对应的组件:
{services.map((item) => ( <div className="space-x-[8px] py-[8px] flex "> <div className="flex flex-col text-center relative px-[8px] py-[8px] items-center active:bg-[#f5f5f5] cursor-pointer"> {(`{<All.${item} sx={{ fontSize: "40px" }} className="text-[#6B84DD] w-[64px] h-[p64x] text-3xl" />}`)} <span className=" font-merrisans text-[14px] font-semibold"> {item} </span> </div> </div> ))}
效果如图:
正确解决方案
React不支持直接通过字符串拼接的方式渲染组件,你需要先从All对象中取出对应的组件,再以JSX组件的方式渲染(注意组件变量名必须大写开头,这是React的规则):
{services.map((item) => { // 从All中取出对应组件,变量名大写开头 const Component = All[item]; return ( <div className="space-x-[8px] py-[8px] flex "> <div className="flex flex-col text-center relative px-[8px] py-[8px] items-center active:bg-[#f5f5f5] cursor-pointer"> <Component sx={{ fontSize: "40px" }} className="text-[#6B84DD] w-[64px] h-[64px] text-3xl" /> <span className=" font-merrisans text-[14px] font-semibold"> {item} </span> </div> </div> ); })}
另外注意你原代码里的h-[p64x]是笔误,应该改成h-[64px]。
内容的提问来源于stack exchange,提问作者Shashank Singh
相关产品推荐
相关产品推荐

