React中如何遍历props传入的对象并为不同值渲染对应HTML元素
问题排查
现有代码无内容展示是多个错误共同导致的:
- 变量拼写错误:判断条件里的
allDes[desc]少写了字母c,和定义的对象名allDesc不匹配,触发运行时报错导致渲染中断 - JSX变量未绑定:你写的
<h1>allDesc.description</h1>会直接输出纯文本,需要用{}包裹才能读取对象的实际值 - 遍历逻辑错误:对
allDesc的所有key做遍历时,每次循环都会返回全部4个标签,最终会重复渲染多组相同内容,不符合需求 - 字段定义错误:定义
allDesc时重复写了两次description3,还缺少description2字段,会导致对应位置读取到undefined
正确实现
如果你的字段是固定的4个,不需要动态遍历,直接渲染即可:
// 先修正对象定义,删除重复的description3,补充缺失的description2 const allDesc = { description: "Title Description", description1: "Intro Description", description2:"Sub title", description3: "Sub Description" } // 渲染逻辑 <div> {allDesc.description && <h1>{allDesc.description}</h1>} {allDesc.description1 && <p>{allDesc.description1}</p>} {allDesc.description2 && <h3>{allDesc.description2}</h3>} {allDesc.description3 && <p>{allDesc.description3}</p>} </div>
如果需要动态根据字段名匹配对应的标签,用映射表实现:
const tagMap = { description: 'h1', description1: 'p', description2: 'h3', description3: 'p' } const allDesc = { description: "Title Description", description1: "Intro Description", description2:"Sub title", description3: "Sub Description" } // 渲染逻辑 <div> {Object.entries(allDesc).map(([key, value], index) => { const Tag = tagMap[key] return value ? <Tag key={index}>{value}</Tag> : null })} </div>
内容的提问来源于stack exchange,提问作者Rinael
相关产品推荐
相关产品推荐

