首页 > 解决方案 > Semantic-UI React Dropdown - 使用 Enter 键

问题描述

我有一个来自语义 UI React 的下拉组件(https://react.semantic-ui.com/modules/dropdown/)。

目前,Dropdown 填充来自 API 调用的数据,该调用返回:

[
{href: 'https://blah blah.com',
text: 'text to display in the dropdown'}
]

下拉菜单中有显示为项目的文本,它们是指向外部网页的链接。我可以输入搜索内容,单击列表中的项目,然后我会转到该特定下拉项目的链接。我想做的是能够搜索该项目并单击 Enter 键以选择该项目并转到该项目的链接。有谁知道我该怎么做?目前,按 Enter 只会选择该项目并将其显示在下拉搜索中,而不会实际触发指向该项目的链接。

这是我的代码:

import React, { Component } from "react";
import { Dropdown } from "semantic-ui-react";

const snippets = [];

class SearchableDropdown extends Component {
  state = {
    success: false,
    textValue: "",
    topic: this.props.topic,
    data: [],
  };


  async componentDidMount() {
    let topics = window.location.pathname;
      
    const res = await fetch(`http://localhost:5000/api${topics}`);

    const jsonData = await res.json();
    const info = jsonData;
    const data = Object.keys(info).map((key) => {
      return {
        topic: info[key].topic,
        card_title: info[key].card_title,
        card_subtitle: info[key].card_subtitle,
        card_gif: info[key].card_gif,
        card_link: info[key].card_link,
      };
    });
    this.setState({ data });

    let topicInfo = this.state.data;
    topicInfo.forEach((item) =>
      snippets.push({
        text: `${item.card_title} | ${item.card_subtitle}`,
        value: `${item.card_title} | ${item.card_subtitle}`,
        href: `${item.card_link}`,
      })
    );
    }
  }

  render() {
    let topic = this.props.topic;

    return (
      <Dropdown
        placeholder="Search Snippets"
        fluid
        search
        selection
        options={snippets}
        onChange={this.handleChange}
        style={{
          backgroundColor: "whitesmoke",
          border: "1px solid black",
          display: "block",
          margin: "auto",
          width: "50%",
          marginTop: "30px",
        }}
      />
    );
  }
}

export default SearchableDropdown;

标签: reactjssemantic-uisemantic-ui-react

解决方案


推荐阅读