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

ReactJS删除Material-UI TextField值仍显示旧输入内容如何解决

问题根源

你遇到的问题本质是受控组件切换为非受控模式导致的状态不同步:
Material-UI的TextField作为受控组件使用时,若value属性接收到undefined/null,会自动切换为非受控模式,此时输入框的显示内容不受外部传入的value控制。你在初始化text状态、调用setText()清空时都没有显式传入空字符串,导致text变为undefined,触发了这个问题。

修复方案

方案1:快速修复现有代码

修改3处代码即可:

  1. 给SearchBar内部的text状态设置初始值为空字符串
// 原代码
const [text, setText] = useState()
// 修改为
const [text, setText] = useState('')
  1. 清空时显式传入空字符串,不要不传参数
// 原清空代码
setSearch()
searchBarRef.current.setText()
// 修改为
setSearch('')
searchBarRef.current.setText('')

方案2:优化为完全受控组件(推荐)

不用在SearchBar内部维护独立状态,直接复用父组件的状态,避免多状态同步问题,也不需要操作ref:

修改后的SearchBar代码:

import React, { forwardRef } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { TextField } from '@material-ui/core';

import Colors from '../globals/Colors';

const useStyles = makeStyles({
  textFieldLabel: {
    fontSize: 18,
    "&$focusedLabel": {
      color: Colors.firstColor,
      backgroundColor: Colors.whiteColor,
    },
  },
  focusedLabel: {}
})

// 新增value prop,去掉内部state
function SearchBar({ label, onChange, className, value }, ref) {
  const classes = useStyles()

  return (
    <TextField
      label={label}
      variant="outlined"
      size="small"
      className={className}
      value={value}
      InputLabelProps={{
        classes: {
          root: classes.textFieldLabel,
          focused: classes.focusedLabel
        }
      }}
      onChange={(event) => {
        onChange(event.target.value)
      }}
    />
  )
}

export default forwardRef(SearchBar)

父组件调用代码:

<SearchBar
   label={currentUser.role === 1 ? i18n.t('dashboard.searchAdmin') : i18n.t('dashboard.search')}
   className={classes.search}
   value={search} // 传入父组件的search状态
   onChange={(value) => setSearch(value)}
/>

清空代码:

只需要修改父组件状态即可,不需要操作ref

setSearch('')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 23:09:05