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

MUI TextField中InputProps图标点击无法获取输入值的问题

问题解答

这个点击事件不是来自TextField,而是直接来自你点击的AddIcon组件。

原因很简单:当你点击endAdornment里的图标时,事件的触发目标就是这个图标元素,而图标本身并没有value属性,所以e.target.value自然是undefined。

要获取TextField的输入值,你可以用以下两种常用方式:

方式1:受控组件绑定状态

把TextField设为受控组件,用状态同步输入值,点击图标时直接读取状态即可:

import { useState } from 'react';
import TextField from '@mui/material/TextField';
import AddIcon from '@mui/icons-material/Add';

function TagInput() {
  const [tagName, setTagName] = useState('');

  const handleTagAdd = () => {
    console.log(tagName); // 直接使用状态中的输入值
    // 这里执行添加标签的逻辑
  };

  return (
    <TextField
      id="outlined-basic"
      label="Type Tag Name"
      variant="outlined"
      fullWidth
      value={tagName}
      onChange={(e) => setTagName(e.target.value)}
      InputProps={{
        endAdornment: <AddIcon sx={{ cursor: "pointer" }} onClick={handleTagAdd} />,
      }}
    />
  );
}

方式2:使用ref获取输入框值

通过inputRef获取TextField对应的DOM输入元素,直接读取其value属性:

import { useRef } from 'react';
import TextField from '@mui/material/TextField';
import AddIcon from '@mui/icons-material/Add';

function TagInput() {
  const inputRef = useRef(null);

  const handleTagAdd = () => {
    const inputValue = inputRef.current?.value;
    console.log(inputValue); // 获取输入框当前值
    // 这里执行添加标签的逻辑
  };

  return (
    <TextField
      id="outlined-basic"
      label="Type Tag Name"
      variant="outlined"
      fullWidth
      inputRef={inputRef}
      InputProps={{
        endAdornment: <AddIcon sx={{ cursor: "pointer" }} onClick={handleTagAdd} />,
      }}
    />
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 06:57:17