React功能组件重新渲染未显示

时间:2019-12-10 13:11:08

标签: javascript reactjs react-hooks

我正在尝试通过将jquery下拉框移植到React来学习React和钩子。我遇到的问题是,当我选择一个选项时,它不会显示在应该显示所选选项的div中。我的代码是:

export const ReactDropdown: React.FC<IDropdownProps> = (props) => {
  const [options, setOptions] = React.useState([]);
  const [selectedOptions, setSelectedOptions] = React.useState([]);

  React.useEffect(() => {
    if(options.length === 0) {
      if(React.Children.count(props.children) > 0) {
        var optionsList: ReactDropdownOption[] = [];
        var index: number = 0;
        React.Children.forEach(props.children, function(item) {
          var entry = {
            value: (item as React.ReactElement).props.value,
            text: (item as React.ReactElement).props.children,
            index: index
          }
          index++;
          optionsList.push(entry);
        });
        setOptions(optionsList);
      }
    }
  });

  const itemSelect = (evt: React.MouseEvent): void => {
    var item = evt.currentTarget as HTMLLIElement;
    if(item.className == 'disabled-result') {
      return;
    }

    var option = {
      text: item.innerText,
      value: item.dataset.value,
      index: parseInt(item.dataset.index),
      className: props.allowSingleDeselect || (props.isMultiple && selectedOptions.length > 0) ? 'search-choice' : ''
    }

    var currentOptions = props.isMultiple ? [...selectedOptions] : [];
    currentOptions.push(option);
    setSelectedOptions(currentOptions);
    item.className = 'disabled-result';

    if(props.onChange) {
      props.onChange(currentOptions);
    }
  }

  return (
    <div>
      <div className='dropdown-container' tabIndex={0}>
        <div className='results-container'>
          <div className='dropdown-container inner'>
            {selectedOptions.map((item) => {
              <span className='result' data-index={item.index} data-value={item.value} key={'selected-option-' + item.index}>{item.text}</span>
            })}
            <span className='result-search'><input type='text' onClick={openOptions} /></span>
          </div>
        </div>
      </div>
      <div clssName='options-container'>
        <ul>
          {options.map((item) => (
            <li data-index={item.index} data-value={item.value} className='active-result' onClick={itemSelect} key={'option-' + item.index}>{item.text}</li>
            ))}
        </ul>
      </div>
    </div>
  );
}

options.map可以完美运行,并且所有选项均以应有的方式呈现。当我选择一个选项时,itemSelect正在触发。 itemSelect触发后,再次返回触发。如果我在selectedOptions.map中放置一个断点,则所有的selectedOptions都将被映射,但是HTML要么从不呈现,要么不显示,我也不知道为什么。有人可以告诉我我在做什么错吗?

这是一个显示错误的CodePen: CodePen

0 个答案:

没有答案