ReactJS实现数组元素转表格行的组件开发问题
React 实现数组元素生成表格行
问题中的错误点
- 组件命名不符合React规范:React要求自定义组件名必须首字母大写,你的
myRows应该改成MyRows,否则React会把它当作原生HTML标签处理,导致渲染失败。 - JSX变量渲染错误:直接写
entry.name会被当作字符串输出,正确做法是用大括号包裹变量,比如{entry.name}。 - 标签闭合错误:代码里的
<td>E4/</td>存在语法错误,应改为<td>E4</td>。
正确代码实现
App.js
import MyRows from './MyRows'; const MyApp = ({ values }) => { return ( <table> <thead> <tr> <th>姓名</th> <th>姓氏</th> <th>列3</th> <th>列4</th> <th>值22</th> <th>列6</th> <th>列7</th> </tr> </thead> <tbody> {/* 遍历values数组,为每个元素生成一行 */} {values.map((entry, index) => ( <MyRows entry={entry} key={index} /> ))} </tbody> </table> ); }; export default MyApp;
MyRows.js
const MyRows = ({ entry }) => { return ( <tr> <td>{entry.name}</td> <td>{entry.secondName}</td> <td>C</td> <td>D1</td> <td>{entry.value22}</td> <td>E3</td> <td>E4</td> </tr> ); }; export default MyRows;
额外注意事项
- 关于
key:如果数组中的每个entry有唯一标识(比如id),建议用entry.id作为key,比index更稳定,避免列表更新时出现渲染异常。 - 空数组处理:如果
values可能为空或未定义,可以用可选链操作符做容错处理:{values?.map(...)},避免map调用报错。
内容的提问来源于stack exchange,提问作者Tangodo
相关产品推荐
相关产品推荐

