Javascript 使用 React 组件自动完成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31803890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Autocomplete with React components
提问by Jesvin Jose
I want a autosuggest workflow like below. Instead of displaying numeric ID, say 123 in a text field, I want to show custom information.
我想要一个如下所示的自动建议工作流程。我想显示自定义信息,而不是在文本字段中显示数字 ID,比如 123。
While I can do the rest with React, I still need to do autocomplete. I have two requirements:
虽然我可以用 React 完成剩下的工作,但我仍然需要自动完成。我有两个要求:
- When selected, provide a callback with rich data
{id: 123, title:"Prince Hall", info:"123 Foo St"}
- Have custom rendering that allows me to reuse JSX templates
- 选择后,提供具有丰富数据的回调
{id: 123, title:"Prince Hall", info:"123 Foo St"}
- 有自定义渲染,允许我重用 JSX 模板
JQueryUI and Twitter autocompletes have both features. But their item rendering takes is string based, but I want to reuse JSX templates which are virtual-dom based. I dont want to duplicate/hardcode JSX templates with string templates.
JQueryUI 和 Twitter 自动完成功能都具有。但是他们的项目渲染需要基于字符串,但我想重用基于虚拟 dom 的 JSX 模板。我不想用字符串模板复制/硬编码 JSX 模板。
回答by Erwin Mayer
Check out react-select. It is simple, beautiful and currently has the most Github stars. Live demo here.
查看react-select。它简单、美观,目前拥有最多的 Github 星星。现场演示在这里。
回答by Jesvin Jose
React-Autosuggest is a component that meets the requirements. It has custom rendering that works natively with React elements.
React-Autosuggest 是满足需求的组件。它具有本地与 React 元素一起工作的自定义渲染。
We can make it handle JS objects instead of plain strings.
我们可以让它处理 JS 对象而不是普通字符串。
- the
onSuggestionSelected
props is a callback to get the selected suggestion suggestionRenderer
method takes suggestion and returns React markup
- 该
onSuggestionSelected
道具是一个回调来获得所选择的建议 suggestionRenderer
方法接受建议并返回 React 标记
回答by Alex Trn
Another powerful Auto-Complete/Auto-Suggest module is 'downshift' which has a wide variety of props for better customization. Different from react-select which opens as a select-box, downshift is a textbox which unhides a suggestion list of words as its value changes.
另一个强大的 Auto-Complete/Auto-Suggest 模块是“降档”,它具有多种道具,可以更好地进行自定义。与作为选择框打开的 react-select 不同,downshift 是一个文本框,当它的值发生变化时,它会取消隐藏单词的建议列表。