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

ReactJS通过props渲染列表项的代码补全问题求解

React 列表渲染代码填空题补全方案

题目规则

  • 不得修改题目给出的默认代码,仅可在注释标注的位置补充代码
  • 实现目标:在React中通过props传递数据完成列表渲染

补全后完整可运行代码

import ReactDom from 'react-dom'

function ListItem(props) {
  //return a list item
  return <li>{props.name}</li>
}

function MyList(props){
  const stuff = props.stuff
  const listItems = stuff.map(item => ( //write a function to create list
  <ListItem key={item.id} name={item.name} //props for calling listitem />
  ));
  return(
    <ul>
    {listItems}
    {/* display list items */}
    </ul>
  )
}

const stuff = [
  {id: 1, name: 'hi'},
  {id: 2, name: 'hii'},
  {id: 3, name: 'hiiii'},
  {id: 4, name: 'hiiiiiii'}
]

ReactDom.render(
//give write component name here
<MyList stuff={stuff} />
,document.getElementById('root'))

补全逻辑说明

  • ListItem组件:接收父组件通过props传入的name字段,返回标准<li>列表项标签
  • 列表项数组生成:通过数组map方法遍历传入的stuff数组,为每一条数据生成对应的ListItem组件,同时传入React列表渲染要求的唯一key值(复用数据自带的id字段避免渲染警告),以及列表项需要展示的name字段
  • 列表挂载位置:在<ul>标签内通过JSX插值语法插入提前生成的listItems数组,即可完成批量列表渲染
  • 根节点渲染:将携带stuff数据源的MyList组件传入ReactDom.render方法,挂载到id为root的DOM节点即可完成整体渲染

内容的提问来源于stack exchange,提问作者Tejendra Singh Rajawat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 07:15:32