繁体   English   中英

从数组动态加载React组件的子集

[英]Dynamically load a subset of React components from an array

我有一个React组件ItemsContainer,我想在其中渲染一组Item(每个都在新行中)。 ItemsContainer接收两个道具, items是它应该渲染的Item组件的数组,而numberOfItems是一个数字,表示我一次要渲染多少个项目。 每个项目都有一个按钮,辞退,应该让当前项消失,导致容器中的其他项目上移,并在接下来的项目items出现(相同流上的社交媒体网站驳回通知)。 我无法弄清楚:1.如何一次仅渲染numberOfItems Items 2.如何在单击某个项目并使其显示下一个项目时使该项目消失,而又不会触发其他项目的重新渲染

我使用Array.map渲染项目,但是当我只想渲染它们的某个子集时,这一次渲染了所有项目,然后还试图弄清楚如何处理解雇的逻辑。

您可以使用filter来获取尚未取消的项目,然后将splice应用于其余项目以限制渲染的数量:

 const items = [{ id: 0, message: 'Test 1'},{ id: 1, message: 'Test 2'},{ id: 2, message: 'Test 3'},{ id: 3, message: 'Test 4'},{ id: 4, message: 'Test 5'},{ id: 5, message: 'Test 6'}] class App extends React.Component { state = { notifications: items, displayAmt: 2 }; renderNotifications = () => { const { notifications, displayAmt } = this.state; // First, filter out all notifications that have been dismissed // Then, splice the remaining items to only get n amount at a time // Last, map over the remaining items and render them return notifications.filter( notification => !notification.dismissed ) .splice(0, displayAmt) .map( notification => ( <li onClick={() => this.dismissNotification(notification.id)} key={notification.id}> {notification.message} </li> )); }; dismissNotification = id => { // Use the id passed in to update the item in state from dismissed: false -> true const notifications = this.state.notifications.map( notification => { if(notification.id === id) { notification.dismissed = true; } return notification; }); this.setState({ notifications }); }; render() { const notifications = this.renderNotifications(); return ( <ul> {notifications} </ul> ) } } ReactDOM.render(<App/>, document.getElementById('root')); 
 li { cursor: pointer; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM