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>
      )}
相关推荐
FreeTinker6 小时前
HTML本地存储技术解析:localStorage与sessionStorage的原理、差异与应用场景
前端·html
qq_452396236 小时前
第十二篇:《全链路监控与可观测性:前端错误追踪与性能分析》
前端
海兰7 小时前
【应用】基于 Next.js 16 + Python mplfinance的金融K线图与技术指标可视化平台(三)
javascript·python·金融
wangruofeng7 小时前
Phosphor Icons 官网源码拆解:URL 即存储、水波动画与 7362 Star 图标库的架构实践
前端·架构·github
BigTopOne7 小时前
WebRTC Native / Android 开发学习资源整理
前端
excel8 小时前
nuxt 3 升级 nuxt 4 报错之 hasInjectionContext
前端
小磊哥er8 小时前
深入解构Claude Code - 第 7 篇 · 连接外面的世界
javascript·ai编程
何以解忧,唯有..9 小时前
LangChain 工具调用(Tool Calling)实战指南
java·前端·langchain
小磊哥er9 小时前
深入解构Claude Code - 第 6 篇 · 终端里的图形界面
javascript·ai编程