reactjs - 以编程方式显示 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
这是一张图片:
该下拉插入符号图标应显示与单击框中相同的所有结果:
解决方案
您可以通过关注输入来触发下拉菜单。为此,只需为其创建一个引用:
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
推荐阅读
- c# - 优化渲染纹理
- gitlab - 如何在 GitLab 中自定义构建触发器
- android - Google Play 计费库 2.0:是否必须确认旧的非消耗性购买?
- r - 如何使用滑块在 RShiny 中动态选择输入数量
- c# - 如何计算动画师的动画完成所需的时间?
- unity3d - 有谁知道如何从播放模式中删除世界图标中的 TextMeshPro?
- php - 导出到 xlsx 文件时,20 位数字将显示 15 位数字后跟 5 个零
- unity3d - 3D播放器和2D地板。我有对撞机问题
- postgresql - 在 Google Cloud SQL 中授予所有权限
- python - Pymongo:如何将集合设置中的许多文档更新为列表的值元素