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

如何生成带空值的React.ChangeEvent<HTMLInputElement>触发输入框清空

基于Chakra-UI开发带清空功能的React输入组件的问题

我正在基于Chakra-UI开发一个自定义React输入组件,点击图标按钮可将输入值清空为""。当前需要解决的核心问题是:清空操作时要给onChange函数传递一个React.ChangeEvent<HTMLInputElement>事件,让该组件能和普通Chakra UI输入组件一样正常使用。

第一次尝试:从零构建新事件

我写了以下组件代码,但不知道在按钮点击事件里如何生成符合要求的onChange事件:

import React, { useState } from "react"
import { IconButton, InputGroup, InputGroupProps, InputProps, InputRightElement, Input } from "@chakra-ui/react"
import { MdClose } from "react-icons/md";

export type CleanableInputProps = InputProps & { 
  Input?: (props: InputProps) => JSX.Element,
  inputGroupProps?: InputGroupProps,
}

export const CleanableInput = ({
  inputGroupProps = {}, // 允许给外层容器注入props
  ...props
}: CleanableInputProps): JSX.Element => {

  const [search, setSearch] = useState<CleanableInputProps['value']>(props?.value);
  const _setSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearch(e.currentTarget.value); // 更新React状态值
    props.onChange?.(e);
  }

  return (
    <InputGroup {...inputGroupProps}>
      <Input {...props} value={search} onChange={_setSearch} />
      <InputRightElement>
        <IconButton  icon={<MdClose />} aria-label="clean" onClick={() => {

          //
          // 需要创建值为""的Input onChange事件
          // e = __________________;
          //

          _setSearch(e);

        }}/>
      </InputRightElement>
    </InputGroup>
  )
}

第二次尝试:通过Ref更新输入框并触发onChange

我尝试用输入框Ref更新值后手动触发事件,但遇到两个问题:

  • 无法兼容Chakra UI以外的其他输入组件;
  • 输入框值已视觉上变为空白,但onChange事件从未触发。
import React, { useRef } from "react"
import { IconButton, InputGroup, InputGroupProps, InputProps, InputRightElement, Input } from "@chakra-ui/react"
import { MdClose } from "react-icons/md";

export type CleanableInputProps = InputProps & {
  inputGroupProps?: InputGroupProps,
}

export const CleanableInput = ({
  inputGroupProps = {}, // 允许给外层容器注入props
  ...props
}: CleanableInputProps): JSX.Element => {

  const inputRef = useRef<HTMLInputElement | null>(null);

  return (
    <InputGroup {...inputGroupProps}>
      <Input {...props} ref={inputRef} value={props.value} />
      <InputRightElement>
        <IconButton icon={<MdClose />} aria-label="" onClick={() => {
          if (inputRef != undefined && inputRef.current != undefined) {
            // 更新值(正常生效)
            inputRef.current.value = "";

            // 手动触发onChange事件(未生效)
            let event = new Event('input', { bubbles: true });
            inputRef.current.dispatchEvent(event);
          }
        }} />
      </InputRightElement>
    </InputGroup>
  )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:57:25