在React的render()方法中显示选定的选项

时间:2018-06-30 10:14:00

标签: reactjs dropdown office-ui-fabric

我正在学习React,我正在努力实现以下目标: 我正在使用下拉列表,该列表允许用户选择多个项目。然后,我试图在数组中添加每个选定的选项。然后,我试图在render方法中显示选定的项目(选项),但是它不起作用。

稍后,我想将此组件转换为可重用的组件,以便执行级联。

所以,我的问题是:

1) how can I add each selected option into an array
2) iterate through the array and display items inside the render method
3) how to make this component reusable

enter image description here

下图显示数组的长度为1,但是我无法显示项目。它是空的。 enter image description here

下面我将包含到目前为止的代码:

import * as React from 'react';
import { PrimaryButton } from 'office-ui-fabric-react/lib/Button';
import { Dropdown, IDropdown, DropdownMenuItemType, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown';

import './Dropdown.Basic.Example.scss';
import { IBaseProps,BaseComponent, createRef } from 'office-ui-fabric-react';

export interface IDropdownBasicExampleProps extends IBaseProps {
  loadOptions: () => Promise<IDropdownOption[]>;
  onChanged: (option: IDropdownOption, index?: number) => void;
}

export interface IDropdownBasicExampleState {
    selectedItem?: IDropdownOption;
    selectedItems: IDropdownOption[];
    loading: boolean;
    options: IDropdownOption[];
    selectedKey: string | number;
    error: string;
}
export class DropdownBasicExample extends BaseComponent<IDropdownBasicExampleProps,IDropdownBasicExampleState> {
  private _basicDropdown = createRef<IDropdown>();
  private selItem:IDropdownOption;
  constructor(props:IDropdownBasicExampleProps,state:IDropdownBasicExampleState) {
    super(props);
    this.state = {
      selectedItem: undefined,
      selectedItems: new Array<IDropdownOption>(),
      loading: true,
      error: undefined,
      options: undefined,
      selectedKey:""
    };

  }

  public componentDidMount(): void {
    this.loadOptions();
  }


  private loadOptions(): void {
    this.setState({
      loading: true,
      error: undefined,
      options: undefined
    });

    this.props.loadOptions()
      .then((options: IDropdownOption[]): void => {
        this.setState({
          loading: false,
          error: undefined,
          options: options
        });
      }, (error: any): void => {
        this.setState((prevState: IDropdownBasicExampleState, props: IDropdownBasicExampleProps): IDropdownBasicExampleState => {
          prevState.loading = false;
          prevState.error = error;
          return prevState;
        });
      });
  }

  public onChangeMultiSelect = (item: IDropdownOption, index): void => {
    const updatedSelectedItem = this.state.selectedItems ? this.copyArray(this.state.selectedItems) : [];
    if (item.selected) {
      // add the option if it's checked
      updatedSelectedItem.push(item.key);
    } else {
      // remove the option if it's unchecked
      const currIndex = updatedSelectedItem.indexOf(item.key);
      if (currIndex > -1) {
        updatedSelectedItem.splice(currIndex, 1);
      }
    }
    this.setState({
      selectedItems: updatedSelectedItem,
      //selectedItem:item
    });

    if (this.props.onChanged) {
       this.props.onChanged(this.state.selectedItem, index);
    }

    console.log(this.state.selectedItems);
  };

  public copyArray = (array: any[]): any[] => {
    const newArray: any[] = [];
    for (let i = 0; i < array.length; i++) {
      newArray[i] = array[i];
    }
    return newArray;
  };


  public render() {
    const { selectedItem, selectedItems } = this.state;

    return (
      <div className="docs-DropdownExample">

        <Dropdown
          placeHolder="Select options"
          label="Multi-Select controlled example:"
          selectedKey={selectedItem ? selectedItem.key : undefined}
          //selectedKeys={selectedItems}
          onChanged={this.onChangeMultiSelect}

          multiSelect
          options={this.state.options}
        />

    <div>length: {this.state.selectedItems.length}</div>

            {this.state.selectedItems.map((item:IDropdownOption)=>{
              return <div>key: {item.key} {item.selected} {item.text} {item.index}</div>
            })}
       </div>
    );
  }


}

1 个答案:

答案 0 :(得分:1)

第一次定义状态

this.state = {
    checkbox_value: []
}

然后定义复选框,例如:

<input onChange = { this.checkboxValue.bind(this) } value = "0" type="checkbox" />
<input onChange = { this.checkboxValue.bind(this) } value = "2" type="checkbox" /> 

然后使用该功能。

checkboxValue(event){

    let checked_list = this.state.checkbox_value;
    let check =  event.target.checked;
    let value =  event.target.value; 
    if(check){
        this.setState({
            checkbox_value: [...this.state.checkbox_value, value]
        });
    }else{
        var index = checked_list.indexOf(event.target.value);
        if (index > -1){
            checked_list.splice(index, 1);
        }
        this.setState({
            checkbox_value: checked_list
        })
    }

}

然后,您可以使用map()方法的checkbox_value在渲染中显示选中的值。希望对您有用