英文:
Instant Search on Material UI AutoComplete Component
问题
被迫在使用AutoComplete Material UI组件提交表单时按两次回车。我希望只需选择一次选项就能导航到另一个网页。
我尝试过更改提交处理程序和纸张/框组件,但问题仍然存在。一旦我从AutoComplete的下拉菜单中选择一个选项,用户必须再次按回车。
英文:
Forced to press enter twice on form submission with AutoComplete Material UI component. I want to be able to only select the options once to navigate to another web page.
I attempted to change around the submission handler and the paper/box components, but the problem persists. Once I select an option from the dropdown menu from AutoComplete the user has to hit enter again.
答案1
得分: 1
你在AutoComplete组件上实现了即时搜索,使用了useEffect ReactJS。
import React, { useState, useEffect } from 'react';
import { Autocomplete } from '@material-ui/lab';
import { TextField } from '@material-ui/core';
function searchAutocomplete({ option, onSelection }) {
const [searchTermValue, setSearchTermValue] = useState('');
const [filteredOptionValue, setFilteredOptionValues] = useState([]);
useEffect(() => {
setFilteredOptionValues(option.filter((option) =>
option.label.toLowerCase().includes(searchTermValue.toLowerCase())
));
}, [searchTermValue, option]);
return (
<Autocomplete
option={filteredOptionValue}
getOptionLabel={(option) => option.label}
renderInput={(param) => (
<TextField
{...param}
label="Search"
variant="outlined"
onChange={(event) => setSearchTermValue(event.target.value)}
/>
)}
onChange={onSelection}
/>
);
}
希望这段代码对你有帮助。
英文:
You implement instant search on the AutoComplete component, using useEffect ReactJS.
import React, { useState, useEffect } from 'react';
import { Autocomplete } from '@material-ui/lab';
import { TextField } from '@material-ui/core';
function searchAutocomplete({ option, onSelection }) {
const [searchTermValue, setSearchTermValue] = useState('');
const [filteredOptionValue, setFilteredOptionValues] = useState([]);
useEffect(() => {
setFilteredOptionValues(option.filter((option) =>
option.label.toLowerCase().includes(searchTermValue.toLowerCase())
));
}, [searchTermValue, option]);
return (
<Autocomplete
option={filteredOptionValue}
getOptionLabel={(option) => option.label}
renderInput={(param) => (
<TextField
{...param}
label="Search"
variant="outlined"
onChange={(event) => setSearchTermValue(event.target.value)}
/>
)}
onChange={onSelection}
/>
);
}
Hope this code is useful for you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论