簡體   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