React通用列表组件:如何延迟传递子组件参数?
解决思路与实现方案
核心是让AdminList负责把遍历到的每一条数据传递给传入的Row组件,不需要父组件预先绑定数据参数,具体有两种常用实现方式:
方式一:传入组件类型,AdminList内部注入props
父组件只需要把RepositoryRow组件本身传给AdminList,AdminList在遍历showedRepositories时,把当前项的id、record等参数作为props传递给这个组件。
父组件调用示例
<AdminList headerComponent={RepositoryListHeader} rowComponent={RepositoryRow} showedRepositories={filteredRepositories} // 其他通用参数,比如分页、筛选配置等 />
AdminList组件实现
function AdminList({ headerComponent: Header, rowComponent: Row, showedRepositories }) { return ( <div className="admin-list"> <Header /> {/* 表头组件直接渲染,若需参数也可在此传递 */} <div className="list-body"> {showedRepositories.map((repo) => ( <Row key={repo.id} id={repo.id} record={repo} // 还可传递AdminList内部的其他状态,比如选中状态、通用操作回调等 /> ))} </div> </div> ); }
这种方式简洁直观,适合Row组件逻辑相对固定的场景。
方式二:传入渲染函数(Render Prop),灵活传递额外参数
如果需要给Row组件传递父组件的状态或回调,可以用render prop的方式:父组件定义一个接收数据的函数,AdminList遍历数据时调用该函数并传入当前项。
父组件调用示例
<AdminList headerComponent={RepositoryListHeader} renderRow={(record) => ( <RepositoryRow id={record.id} record={record} onDelete={handleDelete} // 父组件的删除回调 isAdmin={currentUser.isAdmin} // 父组件的状态 /> )} showedRepositories={filteredRepositories} />
AdminList组件实现
function AdminList({ headerComponent: Header, renderRow, showedRepositories }) { return ( <div className="admin-list"> <Header /> <div className="list-body"> {showedRepositories.map((repo) => ( <React.Fragment key={repo.id}> {renderRow(repo)} </React.Fragment> ))} </div> </div> ); }
这种方式自由度更高,能灵活组合父组件与AdminList内部的数据。
关键逻辑说明
无论哪种方式,核心都是把数据遍历权留在AdminList内部,父组件只负责提供“渲染模板”,由AdminList在遍历每条数据时注入所需参数,既实现了组件通用性,又解决了参数无法预先定义的问题。
内容的提问来源于stack exchange,提问作者Viktor
相关产品推荐
相关产品推荐

