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

坚强是说给别人听的谎言 提交于 2019-12-02 09:18:05

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 (
    <li><button onClick={this.handleClick}>{isOpen ? 'open' : 'closed'}</button></li>
    )
  }
}


// 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 (<ul>
      {items.map(item => <Item key={item.id} id={item.id} onClick={this.toggleItem} isOpen={item.isOpen} />)}
    </ul>);
  }
}

// AppContainer.js

const itemsFromRedux = [
      { id: '1', isOpen: false },
      { id: '2', isOpen: false },
      { id: '3', isOpen: false },      
    ]

ReactDOM.render(<App items={itemsFromRedux} />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.development.js"></script>
    <div id="root"></div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!