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

如何点击图标按钮清除可复用MUI组件的输入文本?

实现点击图标按钮清除MUI输入框文本的方法

要实现点击图标按钮清除输入框文本,你需要做两个关键修改:让输入框成为受控组件,然后在按钮点击事件中清空绑定的状态值。

步骤1:将输入框设为受控组件

给OutlinedInput添加value属性,绑定到你的tagName状态,确保输入框内容完全由状态控制:

<OutlinedInput
  id={id}
  size="small"
  label={label}
  value={tagName} // 新增:绑定状态到输入框
  onChange={(ev) => updateTagName(ev.target.value)}
  endAdornment={
    <InputAdornment position="end">
      <IconButton onClick={handleClickShowPassword} edge="end">
        {type !== requisitionTabForms.Legal ? (
          <SearchIcon className={classes.iconStyles} />
        ) : (
          <SendIcon />
        )}
      </IconButton>
    </InputAdornment>
  }
/>

步骤2:在按钮点击处理函数中清空输入框状态

修改handleClickShowPassword函数,在完成原有标签添加逻辑后,调用updateTagName('')将tagName设为空字符串,触发输入框内容清空:

const handleClickShowPassword = () => {
  let dupArr: Array<string> = [...tags];
  console.log(tagName);
  if (dupArr && dupArr.length > 0) {
    dupArr.push(tagName);
  } else {
    dupArr = [tagName];
  }

  updateTags(dupArr);
  if (type === requisitionTabForms.Legal && tagCallBack !== undefined) {
    tagCallBack(dupArr);
  }

  // 新增:清空输入框对应的状态
  updateTagName('');
};

如果你的需求是点击按钮仅执行清空操作(无需添加标签),直接保留updateTagName('')逻辑、移除原有标签处理代码即可。

内容的提问来源于stack exchange,提问作者Ryan Fonseka

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 22:57:16