我是编程新手,我想实现一个下拉菜单,用户可以使用向上和向下箭头键浏览下拉菜单,并使用Enter键选择下拉菜单。
我还希望突出显示的下拉菜单项在窗口中对用户可见,而无需使用下拉菜单滚动条。
要实现我在下面实现的代码, 工作正常。但是按下向上箭头键时,突出显示的下拉菜单不在窗口视图中,这意味着它不会滚动查看。
class Dropdownwithinput extends React.PureComponent {
constructor(props) {
super(props);
this.list_item_ref = React.createRef();
this.state = {
input_val: '',
dropdown_values: [],
item_selection: 0,
};
}
componentDidMount = () => {
const values = [
{
id:1,
name: somename,
},
{
id: 2,
name: fname,
},
{
id: 3,
name: lname,
}
],
this.setState({dropdown_values: values});
}
handle_key_down = (event) => {
if (this.state.dropdown_values > 0) {
if (event.keyCode === 38 && this.state.item_selection
> 0) {
this.setState({item_selection:
(this.state.item_selection - 1) %
this.state.dropdown_values.length});
let child_array =
Array.from(this.list_item_ref.current.children);
const element_found = child_array.find(e =>
e.classList.contains("test") &&
e.classList.contains("highlight")
);
element_found && element_found.scrollIntoView();
} else if (event.keyCode === 40) {
this.setState({item_selection:
(this.state.dropdown_values_selection + 1) %
this.state.dropdown_values.length});
let child_array =
Array.from(this.list_item_ref.current.children);
const element_found = child_array.find(e =>
e.classList.contains("test") &&
e.classList.contains("highlight")
);
element_found && element_found.scrollIntoView();
}
if (event.keyCode === 13) {
event.preventDefault();
const selected_item =
this.state.dropdown_values[this.state.user_selection];
const text = this.replace(this.state.input_val,
selected_item);
this.setState({
input_val: text,
dropdown_values: [],
});
}
}
replace = (input_val, selected_item) => {
//some function to replace value in input field with the
//selected dropdown item
}
render = () => {
return (
<input
onChange={this.handle_input_change}
onKeyDown={this.handle_key_down}/>
<div ref={this.list_item_ref}>
{this.state.dropdown_values.map((item, index) => (
<div key={index} className={"test" + (index ===
this.state.item_selection ? ' highlight'
: '')}>
{item.name}
</div>
))}
</div>
)
};
}
}
我认为问题出在handle_key_down方法本身。有人可以帮我解决这个问题。谢谢。