【Material-UI】App Bar 中的搜索框实现详解

Material-UI 是 React 应用中备受欢迎的 UI 库,它提供了丰富的组件和功能来帮助开发者构建现代化的用户界面。本文将深入探讨如何在 App Bar 中实现一个带有主搜索框的设计,从而提升应用的可用性和用户体验。

一、App Bar 概述

1. App Bar 的用途

App Bar 是应用程序顶部的导航栏,通常用于显示应用的标题、导航菜单、通知和搜索框等内容。在现代 Web 应用中,App Bar 不仅承担着导航的作用,还常常包含一些实用功能,如实时搜索、用户个人信息展示等。

2. 为什么要在 App Bar 中添加搜索框?

在用户交互过程中,搜索框是至关重要的工具,尤其是在内容较多的应用中,搜索功能可以显著提升用户的导航效率。因此,许多应用都会在显眼的地方添加搜索框,而 App Bar 是一个理想的位置。将搜索框集成到 App Bar 中,既能保证功能的易用性,也不会干扰其他内容的显示。

二、实现带主搜索框的 App Bar

在本文的示例中,我们将使用 Material-UI 提供的组件,如 AppBarToolbarIconButtonInputBase,并结合 styled 函数自定义搜索框的外观和交互效果。

1. 基本代码结构

首先,我们来看一个实现带主搜索框的 App Bar 的基本代码结构:

import * as React from 'react';
import { styled, alpha } from '@mui/material/styles';
import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box';
import Toolbar from '@mui/material/Toolbar';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import InputBase from '@mui/material/InputBase';
import SearchIcon from '@mui/icons-material/Search';
import AccountCircle from '@mui/icons-material/AccountCircle';

const Search = styled('div')(({ theme }) => ({
  position: 'relative',
  borderRadius: theme.shape.borderRadius,
  backgroundColor: alpha(theme.palette.common.white, 0.15),
  '&:hover': {
    backgroundColor: alpha(theme.palette.common.white, 0.25),
  },
  marginRight: theme.spacing(2),
  marginLeft: 0,
  width: '100%',
  [theme.breakpoints.up('sm')]: {
    marginLeft: theme.spacing(3),
    width: 'auto',
  },
}));

const SearchIconWrapper = styled('div')(({ theme }) => ({
  padding: theme.spacing(0, 2),
  height: '100%',
  position: 'absolute',
  pointerEvents: 'none',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
}));

const StyledInputBase = styled(InputBase)(({ theme }) => ({
  color: 'inherit',
  '& .MuiInputBase-input': {
    padding: theme.spacing(1, 1, 1, 0),
    paddingLeft: `calc(1em + ${theme.spacing(4)})`,
    transition: theme.transitions.create('width'),
    width: '100%',
    [theme.breakpoints.up('md')]: {
      width: '20ch',
    },
  },
}));

export default function PrimarySearchAppBar() {
  return (
    <Box sx={{ flexGrow: 1 }}>
      <AppBar position="static">
        <Toolbar>
          <Typography variant="h6" noWrap component="div">
            MUI
          </Typography>
          <Search>
            <SearchIconWrapper>
              <SearchIcon />
            </SearchIconWrapper>
            <StyledInputBase
              placeholder="Search…"
              inputProps={{ 'aria-label': 'search' }}
            />
          </Search>
          <Box sx={{ flexGrow: 1 }} />
          <IconButton size="large" edge="end" color="inherit">
            <AccountCircle />
          </IconButton>
        </Toolbar>
      </AppBar>
    </Box>
  );
}

2. 代码解读

AppBar 和 Toolbar

AppBar 是 Material-UI 中用于创建应用栏的组件,它通常与 Toolbar 一起使用来布局其中的内容。在我们的示例中,Toolbar 中包含了应用的标题和搜索框。

<AppBar position="static">
  <Toolbar>
    <Typography variant="h6" noWrap component="div">
      MUI
    </Typography>
    {/* 搜索框和其他组件 */}
  </Toolbar>
</AppBar>

AppBarposition="static" 确保应用栏固定在页面顶部,而 Typography 用于显示应用的标题。

搜索框的布局

搜索框由几个部分组成:Search 容器、SearchIconWrapperStyledInputBaseSearch 作为容器,使用了 Material-UI 的 styled 函数来实现自定义样式,主要用于调整搜索框的外观和布局。

const Search = styled('div')(({ theme }) => ({
  position: 'relative',
  borderRadius: theme.shape.borderRadius,
  backgroundColor: alpha(theme.palette.common.white, 0.15),
  '&:hover': {
    backgroundColor: alpha(theme.palette.common.white, 0.25),
  },
  marginRight: theme.spacing(2),
  marginLeft: 0,
  width: '100%',
  [theme.breakpoints.up('sm')]: {
    marginLeft: theme.spacing(3),
    width: 'auto',
  },
}));

这里使用了 alpha 函数来为搜索框设置透明度,并且通过媒体查询调整了在不同屏幕尺寸下的宽度。

搜索图标的处理

SearchIconWrapper 用于包裹搜索图标,并将其固定在搜索框的左侧。由于搜索图标不需要交互,设置了 pointerEvents: 'none',确保图标不会影响用户操作。

const SearchIconWrapper = styled('div')(({ theme }) => ({
  padding: theme.spacing(0, 2),
  height: '100%',
  position: 'absolute',
  pointerEvents: 'none',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
}));
输入框的自定义

StyledInputBase 是我们自定义的输入框组件,它基于 Material-UI 的 InputBase 组件进行了样式调整。为了确保搜索框的输入体验,我们设置了 paddingtransition,并通过媒体查询调整了输入框的宽度。

const StyledInputBase = styled(InputBase)(({ theme }) => ({
  color: 'inherit',
  '& .MuiInputBase-input': {
    padding: theme.spacing(1, 1, 1, 0),
    paddingLeft: `calc(1em + ${theme.spacing(4)})`,
    transition: theme.transitions.create('width'),
    width: '100%',
    [theme.breakpoints.up('md')]: {
      width: '20ch',
    },
  },
}));

三、扩展功能

1. 适配移动端布局

为了确保在移动设备上良好的用户体验,我们可以利用 Material-UI 提供的响应式设计能力。通过调整 Search 和其他组件的布局,我们可以确保在小屏幕上搜索框仍然可以方便地使用。

[theme.breakpoints.up('sm')]: {
  marginLeft: theme.spacing(3),
  width: 'auto',
},

2. 结合其他功能

App Bar 除了可以集成搜索框外,还可以结合通知、消息等功能。通过在 Toolbar 中添加 IconButtonBadge,我们可以轻松实现消息通知功能。

<IconButton size="large" aria-label="show 4 new mails" color="inherit">
  <Badge badgeContent={4} color="error">
    <MailIcon />
  </Badge>
</IconButton>

四、总结

本文介绍了如何在 Material-UI 中实现一个带有主搜索框的 App Bar。我们从基础组件的使用入手,详细讲解了搜索框的布局和样式定制,并展示了如何通过响应式设计适配不同屏幕。借助 Material-UI 强大的自定义能力,开发者可以轻松构建出符合项目需求的 App Bar 组件。

推荐:


在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Peter-Lu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值