Я создал компонент автозаполнения, который получает результаты и показывает их как элементы списка внутри тега ul. всякий раз, когда я нажимаю клавиши со стрелками (вниз или вверх), я падаю вниз по списку, но полоса прокрутки в стороне остается неизменной (она не опускается при выбранном значке li). вот изображение, которое показывает, что я имею в виду: В изображении я перешел к пятому элементу в списке, но полоса прокрутки осталась прежней, хотя пятый элемент выбран.
Как вы видите, ul имеет свойство стиля max-height и переполнение auto, так что оно будет обрезаться. Я пробовал много вещей и не смог найти никакого решения. Оцените любую помощь, опубликуйте мой код здесь.
import * as React from "react";
import { useState, useEffect, useRef } from "react";
const Autocomplete = props => {
const [state, setState] = useState({
// The active selection's index
activeSuggestion: 0,
// The suggestions that match the user's input
filteredSuggestions: [],
// Whether or not the suggestion list is shown
showSuggestions: false,
// What the user has entered
userInput: "",
selected: undefined
});
// Event fired when the input value is changed
const onChange = e => {
const { suggestions } = props;
const userInput = e.target.value;
// Filter our suggestions that don't contain the user's input
const filteredSuggestions = suggestions.filter(
suggestion =>
suggestion.toLowerCase().indexOf(userInput.toLowerCase()) > -1
);
// Update the user input and filtered suggestions, reset the active
// suggestion and make sure the suggestions are shown
setState({
...state,
activeSuggestion: 0,
filteredSuggestions,
showSuggestions: true,
userInput: e.target.value
});
};
// Event fired when the user clicks on a suggestion
const onClick = e => {
// Update the user input and reset the rest of the state
setState({
...state,
activeSuggestion: 0,
filteredSuggestions: [],
showSuggestions: false,
userInput: e.currentTarget.innerText
});
};
// Event fired when the user presses a key down
const onKeyDown = e => {
const { activeSuggestion, filteredSuggestions } = state;
// User pressed the enter key, update the input and close the
// suggestions
if (e.keyCode === 13) {
setState({
...state,
activeSuggestion: 0,
showSuggestions: false,
userInput: filteredSuggestions[activeSuggestion]
});
}
// User pressed the up arrow, decrement the index
else if (e.keyCode === 38) {
if (activeSuggestion === 0) {
return;
}
setState({ ...state, activeSuggestion: activeSuggestion - 1 });
}
// User pressed the down arrow, increment the index
else if (e.keyCode === 40) {
if (activeSuggestion - 1 === filteredSuggestions.length) {
return;
}
setState({ ...state, activeSuggestion: activeSuggestion + 1 });
}
};
let suggestionsListComponent;
if (state.showSuggestions && state.userInput) {
if (state.filteredSuggestions.length) {
suggestionsListComponent = (
<ul className="suggestions">
{state.filteredSuggestions.map((suggestion, index) => {
let className;
// Flag the active suggestion with a class
if (index === state.activeSuggestion) {
className = "suggestion-active";
}
return (
<li className={className} key={suggestion} onClick={onClick}>
{suggestion}
</li>
);
})}
</ul>
);
} else {
suggestionsListComponent = (
<div className="no-suggestions">
<em>No suggestions, you're on your own!</em>
</div>
);
}
}
return (
<>
<input
type="text"
onChange={onChange}
onKeyDown={onKeyDown}
value={state.userInput}
/>
{suggestionsListComponent}
</>
);
};
export default Autocomplete;
body {
font-family: sans-serif;
}
input {
border: 1px solid #999;
padding: 0.5rem;
width: 300px;
}
.no-suggestions {
background-color: #fff;
color: #999;
padding: 0.5rem;
position: absolute;
top: 100%;
}
.suggestions {
position: absolute;
top: 100%;
border: 1px solid #999;
border-top-width: 0;
list-style: none;
margin-top: 0;
max-height: 143px;
overflow-y: auto;
padding-left: 0;
width: calc(300px + 1rem);
}
.suggestions li {
background-color: lighten($color: $deppblue, $amount: 10);
color: #fff;
padding: 0.5rem;
}
.suggestion-active,
.suggestions li:hover {
background-color: lighten($color: $deppblue, $amount: 20);
cursor: pointer;
font-weight: 700;
}
.suggestions li:not(:last-of-type) {
border-bottom: 1px solid #999;
}
<Autocomplete
suggestions={[
"Alligator",
"Bask",
"Crocodilian",
"Death Roll",
"Eggs",
"Jaws",
"Reptile",
"Solitary",
"Tail",
"Wetlands"
]}
/>