首页 > 解决方案 > 以编程方式显示 react-autosuggest 的建议

问题描述

我在这里使用 react-autosuggest 库:https ://react-autosuggest.js.org/ 现在,当用户单击输入框时,输入框下方会弹出输入建议列表,类似于下拉列表. 但我还在输入框中添加了一个很棒的字体向下箭头。单击它时,什么也没有发生。我只是希望它显示与实际输入框相同的列表。

这是我渲染输入组件的方式:

    const renderInputComponent = (inputProps) => (
        <div className="inputContainer">
            {selectedCustomer ? (
                <FontAwesomeIcon
                    icon={faTimes}
                    size={'1x'}
                    onClick={() => {
                        setSelectedCustomer('');
                        setSuggestionValue('');
                    }}
                />
            ) : (
                <FontAwesomeIcon
                    icon={faAngleDown}
                    size={'1x'}
                    onClick={() => {
                      ??? <-- this is where I think I would put something to show those suggestions
                    }}
                />
            )}
            {/*<input {...inputProps} ref={autosuggestInput} />*/}
            <input {...inputProps} />
            {/* when I add in the above commented to code to show options when the caret is clicked, I get an error: https://github.com/moroshko/react-autosuggest/pull/631 */}
        </div>
    );

我创建了一个代码沙箱来展示我的请求。我在我认为代码应该去的地方添加了注释。 https://codesandbox.io/s/compassionate-ramanujan-yi9i8?file=/src/App.js

这是一张图片:

在此处输入图像描述

该下拉插入符号图标应显示与单击框中相同的所有结果:

在此处输入图像描述

标签: reactjsautosuggest

解决方案


您可以通过关注输入来触发下拉菜单。为此,只需为其创建一个引用:

const autosuggestInput = useRef(null);

...

<input {...inputProps} ref={autosuggestInput} />

当点击下拉图标时,调用setFocus()元素

<FontAwesomeIcon
  icon={faAngleDown}
  size={"1x"}
  onClick={() => {
    autosuggestInput.current.focus();
  }}
/>

您可以在此处找到已修复的分叉存储库:https ://codesandbox.io/s/confident-bash-bu789?file=/src/App.js:2875-3047


推荐阅读