How to toggle dynamically generated dropdowns using the .map functions index?

后端 未结 1 1477
遇见更好的自我
遇见更好的自我 2021-01-27 19:33

I have a array that for every item in the array a drop down list is dynamically generated. Right now each drop down list share the same toggle boolean so they all open and close

1条回答
  •  南方客
    南方客 (楼主)
    2021-01-27 20:21

    I can recommend the following pattern to toggle dynamically created elements:

    // Item.js
    
    class Item extends React.Component {
      handleClick = () => {
        const { id, onClick } = this.props;
        onClick(id);
      }
      
      render() {
        const { isOpen } = this.props;
        
        return (
        
  • ) } } // App.js class App extends React.Component { static getDerivedStateFromProps(nextProps, prevState) { const { items } = nextProps; if (items !== prevState.prevPropsItems) { return { items, prevPropsItems: items }; } return null; } state = { prevPropsItems: [], items: [] } toggleItem = id => this.setState(prevState => { const items = prevState.items.map(item => { if (item.id === id) { return { ...item, isOpen: !item.isOpen } } else { return item; } }); return { items } }) render(){ const { items } = this.state; return (
      {items.map(item => )}
    ); } } // AppContainer.js const itemsFromRedux = [ { id: '1', isOpen: false }, { id: '2', isOpen: false }, { id: '3', isOpen: false }, ] ReactDOM.render(, document.getElementById('root'))
    
    
        

    0 讨论(0)
提交回复
热议问题