对物料进行反应ui自动完成元素关注onclick [英] react material ui autocomplete element focus onclick
问题描述
我有一个Material-ui自动填充元素
I have a material-ui autocomplete element
<Autocomplete
id="combo-box-demo"
autoHighlight
openOnFocus
autoComplete
options={this.state.products}
getOptionLabel={option => option.productName}
style={{ width: 300 }}
onChange={this.selectProduct}
renderInput={params => (
<TextField {...params} label="Select Product Name" variant="outlined" />
)}
/>;
当我单击按钮时,我希望此元素获得焦点.
I want this element to get focus when I click a button.
我尝试使用此处所述的引用如何以编程方式对焦点输入做出反应
I tried using references as discribed here how react programmatically focus input
它适用于其他元素,但不适用于自动完成功能
It worked for other elements but not for autocomplete
请帮助
推荐答案
您应该保存对 TextField
组件的引用,并在单击另一个元素后使用此ref进行焦点(一旦发生了某个事件,触发).
You should save a reference to the TextField
component, and use this ref to focus once another element is clicked (once some event was triggered).
let inputRef;
<Autocomplete
...
renderInput={params => (
<TextField
inputRef={input => {
inputRef = input;
}}
/>
)}
/>
<button
onClick={() => {
inputRef.focus();
}}
这里是一个工作示例的链接: https://codesandbox.io/s/young-shadow-8typb
Here is a link to a working example: https://codesandbox.io/s/young-shadow-8typb
您可以使用自动完成"的
openOnFocus
属性来决定是只专注于输入还是要打开自动完成的下拉菜单.
You can play with the
openOnFocus
property of the Autocomplete to decide if you just want focus on the input or you want the dropdown of the autocomplete to open.
这篇关于对物料进行反应ui自动完成元素关注onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!