且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在React中创建级联下拉列表

更新时间:2022-06-01 22:58:51

这篇文章中所述,我将如何实现下拉组件的动态选择的可能方法.通过将组件本身作为另一个下拉列表的子代传递,可以递归使用DropDown组件.

As presented in this post, this is a possible way how I would implement the dynamic selection of a dropdown component. You can use the DropDown component recursively by passing the component itself as a child of another dropdown;

const SomeComponent = () => 'SomeComponent';
const Foo = () => 'Foo';
const Bar = () => 'Bar';

class ListItem extends React.Component {
  handleClick = () => {
    const { option: {id}, onClick } = this.props;
    onClick(id);
  }
  
  render(){
    const { option: { label } } = this.props;
    return (
      <li onClick={this.handleClick}>{label}</li>
    )
  }
}

class DropDown extends React.Component {
  state = {
    selectedOption: null
  }
  
  handleOptionClick = optionId => {
    const { options } = this.props;
    this.setState({ selectedOption: options.find(option => option.id === optionId).child });
  }
  
  render(){
    const { selectedOption } = this.state;
    const { options } = this.props;
    return (
      <ul>
        {options.map(option => (
          <ListItem
            option={option}
            onClick={this.handleOptionClick}
          />
        ))}
        {selectedOption}
       </ul>
     )
  }
}

const DropDownOptions = [
  {id: '1', label: 'label-1', child: <SomeComponent />},
  {id: '2', label: 'label-2', child: <DropDown options={[
    {id: '2-1', label: 'label-2-1', child: <Foo />},
    {id: '2-2', label: 'label-2-2', child: <Bar />}
  ]} />}
]

ReactDOM.render(<DropDown options={DropDownOptions} />, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>