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

后端 未结 1 1478
遇见更好的自我
遇见更好的自我 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 (
        <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>

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