降档:菜单应该关闭,直到找不到结果

Downshift: The menu should close until results not found

我遇到了 Reactjs 前端代码库的问题。我们使用的是库名称 react-autoauggest to achieve the autocomplete functionality but lead has decided to shift from react-autoauggest to downshift。我通读了这个文档并使用 useCombobox 挂钩实现了这个,但他提出了一些问题并告诉我在没有任何指导的情况下解决这些问题。我创建了这些问题的干净版本。

首先我要解决 issue-4 清除按钮应该清除输入字段并关闭菜单。但是当我点击清除按钮时,输入字段是空的,但菜单仍然打开。你能给我一些关于如何在 downshift 中做这些事情的指导吗?

这是我的 codesandbox link 从对象数组中过滤数据: View the Code sandbox here

App.js:

const App = () => {

    // Array of objects
    const [inputItems, setInputItems] = useState(data);

    // State for all primitive types
    const [value, setValue] = useState('');


    /**
     * It will returns the new filtered array.
     * @param data Array<Object> - The array to iterate over
     * @param inputValue {string} - Your input value
     * @return Array<Object> - Returns the new filtered array
     */
    const filterByName = (data, inputValue) => {
        return data.filter(item => {
            return item.name.toLowerCase().indexOf(inputValue.toLowerCase()) !== -1;
        });
    };

    // props for the combobox
    const comboboxProps = {
        className: 'search has-icons-left has-buttons-right'
    };

    // props for the input
    const inputProps = {
        type: 'text',
        className: 'form-control',
        placeholder: 'Enter the state'
    };

    // props for the menu
    const menuProps = {
        className: 'menu'
    };


    // useComboBox
    const {
        isOpen,
        getComboboxProps,
        getInputProps,
        getMenuProps,
        getItemProps,
        highlightedIndex,
        selectItem,
    } = useCombobox({
        items: inputItems,
        onInputValueChange: ({inputValue}) => {
            setValue(inputValue);
            setInputItems(filterByName(data, inputValue));
        },
        itemToString: (item) => item ? item.name : '',
    });



    return (
        <div className="app">
            <div {...getComboboxProps(comboboxProps)}>
                <input {...getInputProps(inputProps)} />
                <span className="icon is-left"><MarkerIcon/></span>
                {(typeof value === 'string' && value.length > 0) ?
                    (<span className="button is-right">
                        <button className="btn btn-clear" onClick={() => selectItem(null)}>Clear</button>
                    </span>) : null}
                {/* Suggestions */}
                <ul {...getMenuProps(menuProps)}>
                    {isOpen && inputItems.map((item, index) => (
                        <li key={index} {...getItemProps({item, index})}
                            style={highlightedIndex === index ? {backgroundColor: "#f5f5f5"} : null}>
                            {item.name}
                        </li>
                    ))}
                </ul>
            </div>
        </div>
    );
};

export default App;

#1,如果没有输入值,防止打开:

<input {
  ...getInputProps({
    ...inputProps,
    onKeyDown: e => {
      if(!value) {
        return e.nativeEvent.preventDownshiftDefault = true 
      }
    }
  })
} />

#2 可能比较棘手,因为如果你想修改状态,过滤器 将被激活。我建议对他们的输入进行一些布局,什么 如果 highlightedIndex > -1

则显示 inputItems[highlightedIndex]
  const completeValue =
    highlightedIndex > -1 ? inputItems[highlightedIndex].name : null;

 return (
   <div className="app">
     ...
{
  completeValue
  ? <input {...getInputProps(inputProps)} value={completeValue} />
    : (
      <input
        {...getInputProps({
          ...inputProps,
          onKeyDown: e => {
            if (!value) {
              return (e.nativeEvent.preventDownshiftDefault = true);
            }
          }
        })}
      />
    )
}
     ...
   </div>
 )

#3、关闭推荐框:

  const {
    isOpen,
    getComboboxProps,
    getInputProps,
    getMenuProps,
    getItemProps,
    highlightedIndex,
    closeMenu, // <= use this inbuilt functionality
    selectItem
  } = useCombobox({

And at the button click just call it by manually:

    <button
      className="btn btn-clear"
      onClick={() => {
        selectItem(null);
        setValue("");
        closeMenu();
      }}
    >
      Clear
    </button>