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>
      )}
相关推荐
默_笙9 分钟前
💫 闭包是个背包:拆解小米前端面试题里的三道"闭包陷阱"
前端·javascript·面试
天若有情67317 分钟前
粒子星空背景单页HTML模板|炫酷动态星空特效网页(纯前端)
前端·html·css动画·网页特效·粒子星空·静态网页模版
工业涂料百问19 分钟前
【趋势前沿】系列(三)工业涂料国产替代的三个台阶:航空、海工、电子的突破路径与认证壁垒
前端
前端snow28 分钟前
ai agent --- agentic RAG
前端
gyratesky41 分钟前
记录一种很新的大屏开发方式
前端·数据可视化
xy34532 小时前
Axure 9.0 中继器核心结构
前端·ui·html·axure·原型·产品设计
老王以为2 小时前
走进 AI Agent 第四篇(上):知识获取管道——RAG 基础
前端·人工智能·全栈
夏天要喝冰可乐2 小时前
一处写作,多平台分发:我给掘金做了一款开源 Chrome 插件
前端·chrome·vibecoding
货拉拉技术2 小时前
货拉拉开源Hadice:安卓 & 鸿蒙桌面调试工具
前端