【问题标题】:Retrieve value from React-Bootstrap Dropdown从 React-Bootstrap 下拉列表中检索值
【发布时间】:2021-11-26 11:37:11
【问题描述】:

我正在尝试获取下拉项的值,例如使用下拉按钮选择的“操作”或“另一个操作”。我知道我需要使用onSelect 事件,但它只给了我href 值,这不是我想要的。任何帮助表示赞赏。

https://react-bootstrap.github.io/components/dropdowns/

  <Dropdown.Toggle onSelect={(e)=> {console.log(e)}} variant="success" id="dropdown-basic">
    Dropdown Button
  </Dropdown.Toggle>

  <Dropdown.Menu>
    <Dropdown.Item href="#/action-1">Action</Dropdown.Item>
    <Dropdown.Item href="#/action-2">Another action</Dropdown.Item>
    <Dropdown.Item href="#/action-3">Something else</Dropdown.Item>
  </Dropdown.Menu>
</Dropdown>

【问题讨论】:

  • 看起来你想要一个select
  • 我认为可以使用他们提供的标记来完成?

标签: javascript html reactjs react-bootstrap


【解决方案1】:

下拉菜单是可切换的上下文叠加层,用于显示链接列表等。

如果您阅读了您提供的链接中的文档,Dropdown.Toggle 没有名为 onSelect 的道具。

也就是说,您可能会添加一些状态并通过数据呈现您的项目。这样您就可以将最后一次点击的Item 保存在状态中。

import { useState } from "react";
import Dropdown from "react-bootstrap/Dropdown";
import "bootstrap/dist/css/bootstrap.min.css";

const items = ["Action", "Another action", "Something else"];

const App = () => {
  const [selectedItem, setSelectedItem] = useState("");

  return (
    <>
      <Dropdown>
        <Dropdown.Toggle variant="success">Dropdown Button</Dropdown.Toggle>
        <Dropdown.Menu>
          {items.map((item) => (
            <Dropdown.Item onClick={() => setSelectedItem(item)}>
              {item}
            </Dropdown.Item>
          ))}
        </Dropdown.Menu>
      </Dropdown>
      <pre>selectedItem: {selectedItem}</pre>
    </>
  );
};

导出默认应用;

【讨论】:

    猜你喜欢
    • 2020-04-11
    • 2020-06-04
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多