如何在React中创建级联下拉列表 [英] how to create cascading dropdown lists in react

查看:101
本文介绍了如何在React中创建级联下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果可以使用office-ui-fabric-react,有人可以告诉我如何创建三个级联下拉列表吗?

Can someone show me how to create three cascading dropdown lists, if it is possible using the office-ui-fabric-react?

另一个问题,当在第一个下拉列表中更改值时,如何重置第二个列表中的索引以将第一项显示为选中状态?

Another question, when the value is changed in the first dropdown, how do you reset the index in the second list to show the first item as selected?

推荐答案

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

这篇关于如何在React中创建级联下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆