React Drop Down-状态在第一次点击时不会更新

时间:2018-09-07 10:39:36

标签: javascript reactjs

我为正在处理的内容创建了一个自定义下拉组件,其想法是您可以通过传递一个名为selectedOption的道具来设置所选选项,或者如果您不通过selectedOption道具,则可以只会将所选选项设置为您单击的项目。当我不传递所选的选项道具时,该组件运行良好,但是当我这样做时,您必须单击两次以更新状态……这好像是该状态落后一步。

这是我的代码:

import React, { Component } from 'react';
import './Dropdown.less';

export default class extends Component {
  constructor(props) {
    super(props);
    this.state = {
      displayAllOptions: false,
      selectedOption: props.selectedOption || props.children[0].props.name
    };
  }

  handleClick = () => {
    if (!this.state.displayAllOptions)
      document.addEventListener('click', this.handleOutsideClick, false);
    else document.removeEventListener('click', this.handleOutsideClick, false);
    this.displayAllOptions(!this.state.displayAllOptions);
  };

  handleOutsideClick = () => this.handleClick();

  displayAllOptions(displayAllOptions) {
    this.setState({ ...this.state, displayAllOptions });
  }

  setSelectedOption = selectedOption =>
    this.setState({ ...this.state, selectedOption });

  componentWillReceiveProps(nextProps) {
    if (this.props.selectedOption) {
      const nextChildren = React.Children.toArray(nextProps.children);

      if (!nextChildren.length) return;

      if (
        nextChildren
          .map(child => child.props.name)
          .indexOf(this.props.selectedOption) === -1
      )
        nextChildren[0].props.callback();
    }
  }

  render() {
    const options = React.Children.map(this.props.children, child =>
      React.cloneElement(child, {
        onClick: () => {
          child.props.callback && child.props.callback();
          !this.props.selectedOption &&
            this.setSelectedOption(child.props.name);
          this.props.selectedOption &&
            this.setSelectedOption(this.props.selectedOption);
        }
      })
    );

    return (
      <div className="dropdown">
        <div>
          <div onClick={this.handleClick} className="selected-option">
            {this.state.selectedOption}     
          </div>
          {this.state.displayAllOptions && (
            <div className="options">{options}</div>
          )}
        </div>
      </div>
    );
  }
}

0 个答案:

没有答案