reactjs - 如何隐藏底部导航图标?
问题描述
几天前,我开始学习 reactjs + material-ui 库,我试图弄清楚如何从 中隐藏图标BottomNavigation
,即:
我在 codesandbox.io 创建了一个mcve。
此外,当我单击登录按钮时,我想知道选择了 BottomNavigation 中的哪个按钮,以便显示一条类似以下内容的消息:
alert(`Page ${name_of_selected_screen} is selected`)
你会怎么做?
解决方案
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
,则未设置page
in 。App
我们可以通过使用useEffect
和useRef
hook 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
。
在这里您的代码框已修改。
推荐阅读
- c++ - 将字符串上传到数据库时出现 wifi 错误的 Arduino Uno r3
- amazon-redshift - 在 AWS Redshift 中,查询取消如何实现完全自动化?
- azure - npm 任务未在 Azure 管道中创建 node_modules 文件夹
- css - 如何将 z-index 应用于范围伪元素
- python - Pandas DF - 按 + Sum 分组,然后为每个类别总计画线
- makefile - 在编译源文件之前有条件地在 Makefile 中运行 bash 脚本
- javascript - FullCalendar:来自谷歌日历的着色事件
- powershell - 使用脚本更改域注册 PC 上的 Tcp/ip 设置
- racket - 如何在 defproc 中使用技术作为合同?
- javascript - 如何从 JavaScript 中的 API 中减去 2 个值