How to toggle dynamically generated dropdowns usin

2020-05-06 13:20发布

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 and the same time, how can I make this work individually?

I map each object to a index here and then start creating dropdowns:

{Object.keys(props.totalWorkload.options).map((item, i) => (
        <WorkloadOptions
          key={i}
          cnt={i}
          appendChoiceList={props.appendChoiceList}
          modalDropDown={props.modalDropDown}
          toggleDropDown={props.toggleDropDown}
          totalWorkloadOptions={props.totalWorkload.options[item]}
        />
      ))}

When the Drop Down options component is created I pass the index to a function:

<div>
    <Dropdown isOpen={props.modalDropDown} toggle={props.toggleDropDown.bind(props.cnt)}>
      <DropdownToggle caret>{props.totalWorkloadOptions.optionTitle}</DropdownToggle>
      <DropdownMenu>
        {props.totalWorkloadOptions.options.map(op => (
          // tslint:disable-next-line:no-invalid-this
          // tslint:disable-next-line:jsx-no-lambda
          <DropdownItem key={op} onClick= {() => props.appendChoiceList(props.totalWorkloadOptions.optionTitle, op)}>
            {op}
          </DropdownItem>
        ))}
      </DropdownMenu>
      <strong> {props.totalWorkloadOptions.optionDescription} </strong>
    </Dropdown>
    <br />
  </div>

The it will arrrive at the following functuion and console log the index and then set the appropriate toggle value in an array to true/false:

  toggleDropDown = (index: any) => {
    console.log('triggered!:' + index);
    let clicked = this.state.modalDropDownClicked;
    // tslint:disable-next-line:no-conditional-assignment
    if (clicked[index]=!clicked[index]){
      this.setState({ modalDropDownClicked: !this.state.modalDropDown[index] });
    }
  };

1条回答
够拽才男人
2楼-- · 2020-05-06 13:44

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>

查看更多
登录 后发表回答