react【实战】搜索框(含联动动画,清空按钮)

效果预览

代码范例

技术栈: react19 + Tailwind CSS

ts 复制代码
  const [isSearchEnable, setIsSearchEnable] = useState(false);
  const [searchValue, setSearchValue] = useState("");
html 复制代码
      {isSearchEnable && (
        <div className="relative">
          <input
            id="search-input"
            className="peer border border-gray-300 px-4 py-2 w-64 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 transition"
            placeholder=" "
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
          />
          <label
            htmlFor="search-input"
            className="absolute left-2 -top-2 bg-white px-2 text-xs text-gray-500 transition-all duration-200 cursor-pointer
                    peer-placeholder-shown:top-2 
                    peer-placeholder-shown:text-sm
                    peer-focus:-top-2 
                    peer-focus:left-2 
                    peer-focus:text-blue-500
                    peer-focus:text-xs"
          >
            搜索
          </label>
          {searchValue && (
            <button
              onClick={() => setSearchValue("")}
              className="absolute right-4 top-2 text-gray-400 hover:text-gray-600 cursor-pointer peer-focus:text-blue-500"
            >
              ✕
            </button>
          )}
        </div>
      )}
相关推荐
掘金一周18 分钟前
想问问掘友们:AI 时代,资深开发的核心价值到底在哪里?| 沸点周刊 7.23
前端·人工智能·后端
橘子星27 分钟前
🚀 手把手带你写一个端侧 AI 应用的"加载进度条"与"聊天对话框"
前端·人工智能
37.2℃9951 小时前
专业的Claude Design解决方案
前端·算法
Jolyne_1 小时前
ng-zorro-table列宽resize后宽度是NaN的源码调试记录
前端
liwulin05061 小时前
【ollama】自定义结构化输出
linux·前端·数据库·ollama
前端甜糖1 小时前
记录We码开发者工具的一个bug
前端·javascript
程序员黑豆2 小时前
鸿蒙应用开发教程:以红绿灯切换为例,掌握条件渲染的核心用法
前端·harmonyos
猫3282 小时前
echarts 日常问题解决
前端·javascript·echarts
新中地GIS开发老师2 小时前
地信职业百科④:GIS开发工程师
前端·数据库·gis·webgis·三维gis开发
我是大卫2 小时前
【图】React源码解析-从数据结构、调度器、源码设计模式到状态计算引擎,深挖useReducer原理
前端·react.js·源码