You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现带圆角底部下划线的Input组件:自适应宽度并设宽限

解决Input组件外层div自适应宽度并限制宽幅的问题

你需要调整外层容器和input元素的样式,让容器能根据输入内容自适应宽度,同时满足最小/最大宽度限制,具体修改如下:

核心修改点

  • 外层div添加inline-block使其由内部元素撑开宽度,同时设置min-w-[100px]和max-w-[300px]限制宽幅
  • input设置w-full填满容器,确保下划线和容器宽度一致;添加text-nowrap避免内容换行,超出时可横向滚动

修改后的代码

import React, { memo, useState } from 'react'
import { CommonInputProps } from '../Input'
import { twMerge } from 'tailwind-merge'

export interface NoStyleProps
  extends Omit<CommonInputProps, 'form' | 'placeholder'> {
  mainDivClass?: string
}

const NoStyle = ({
  register,
  className,
  hasError,
  mainDivClass,
}: NoStyleProps) => {
  const [isFocused, setIsFocused] = useState(false)

  const handleFocus = () => {
    setIsFocused(true)
  }

  const handleBlur = () => {
    setIsFocused(false)
  }

  return (
    <div className={twMerge('relative inline-block min-w-[100px] max-w-[300px]', mainDivClass)}>
      <input
        type="text"
        className={twMerge(
          `outline-none bg-white text-center w-full text-nowrap`,
          className,
        )}
        autoComplete="off"
        {...register}
        onFocus={handleFocus}
        onBlur={handleBlur}
      />
      {hasError && (
        <div className="absolute bottom-0 left-0 right-0 h-1 bg-error rounded-full"></div>
      )}
      {isFocused && !hasError && (
        <div className="absolute bottom-0 left-0 right-0 h-1 bg-primary rounded-full"></div>
      )}
    </div>
  )
}

export default memo(NoStyle)

说明

  1. inline-block让外层div不再占用父容器全宽,仅根据内部input的内容宽度自适应
  2. min-w-[100px]和max-w-[300px]确保容器宽度始终保持在100px到300px区间内
  3. input的w-full保证其宽度与容器完全匹配,下划线元素通过left-0 right-0自动对齐容器宽度
  4. text-nowrap确保输入内容不换行,超出max-width时input会显示横向滚动条,维持容器宽度稳定

内容的提问来源于stack exchange,提问作者Nilton Schumacher F

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 01:05:21