首页 > 解决方案 > 如何隐藏底部导航图标?

问题描述

几天前,我开始学习 reactjs + material-ui 库,我试图弄清楚如何从 中隐藏图标BottomNavigation,即:

展示

我在 codesandbox.io 创建了一个mcve

此外,当我单击登录按钮时,我想知道选择了 BottomNavigation 中的哪个按钮,以便显示一条类似以下内容的消息:

alert(`Page ${name_of_selected_screen} is selected`)

你会怎么做?

标签: reactjsmaterial-ui

解决方案


Ciao,隐藏图标只是需要从 中删除icon道具BottomNavigationAction。这是简单的部分。

要将选择的屏幕传递SimpleBottomNavigation给父级App,这有点棘手。首先,您知道从BottomNavigation onChange函数中检索所选页面的 id。因此,您可以创建一个常量数组SimpleBottomNavigation来映射索引和页面名称之间的相关性。就像是:

const pages = [
   { page: "Page1", id: 0 },
   { page: "Page2", id: 1 },
   { page: "Page3", id: 2 }
];

好的,现在我们必须从 to 传递SimpleBottomNavigation数据App。你可以通过添加一个道具来做到这一点SimpleBottomNavigation

<SimpleBottomNavigation pageSelected={setPageSelected} />

该函数setPageSelected如下所示:

const setPageSelected = (page) => {
   setPage(page);
};

setPage状态的设置状态动作在哪里page

const [page, setPage] = React.useState("");

好吧,现在BottomNavigation onChange让我们pageSelected这样称呼:

props.pageSelected(pages.filter((el) => el.id === newValue)[0].page);

这可行,但选择的第一页有问题。在启动时,如果您不单击任何BottomNavigationAction,则未设置pagein 。App

我们可以通过使用useEffectuseRefhook on来解决这个问题SimpleBottomNavigation

const firstrender = React.useRef(true);
  React.useEffect(() => {
    if (firstrender.current) {   // this is just a technique to run below code just one time
      props.pageSelected(pages.filter((el) => el.id === value)[0].page);
      firstrender.current = false;
    }
  });

现在只需要修改按钮 Login onClick

<Button
   onClick={() => {
      alert("Page: " + page + " is selected");
   }}
>
   Login
</Button>

完毕!现在警报显示在 上选择的页面SimpleBottomNavigation

在这里您的代码框已修改。


推荐阅读