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

如何处理Formik状态,正确显示文件上传的文件名?

问题分析与解决方法

你的问题出在values.files.item.name这行代码上:

  • values.files是FileList对象,item是它的方法(调用语法为item(index)),不是属性,直接写item会输出字符串"item",这就是你看到错误内容的原因。
  • 因为你开启了multiple属性,用户可选择多个文件,所以需要遍历FileList来展示所有选中的文件名。

修正后的代码示例

<div className="mb-3">
  <Heading type="h6-small-bold">
    <label htmlFor="files">Upload Files</label>
  </Heading>
  <input
    type="file"
    role="input"
    className="form-control my-2"
    id="files"
    multiple
    onChange={(event: ChangeEvent) => {
      setFieldValue(
        'files',
        (event.target as HTMLInputElement).files
      );
    }}
  />
  {/* 显示已选文件名列表 */}
  {values.files && values.files.length > 0 && (
    <div className="mt-2">
      <span>已选择文件:</span>
      <ul>
        {Array.from(values.files).map((file, index) => (
          <li key={index}>{file.name}</li>
        ))}
      </ul>
    </div>
  )}
  {errors.files && touched.files ? (
    <div className="alert alert-danger">
      {errors.files.toString()}
    </div>
  ) : null}
</div>

额外说明

  1. 单个文件场景:如果不需要多文件上传,去掉multiple属性后,可直接显示单个文件名:
    {values.files?.[0]?.name && <div className="mt-2">已选择文件:{values.files[0].name}</div>}
    
  2. 初始值处理:确保Formik的initialValues里files初始值设为null或undefined,避免页面加载时报错:
    initialValues={{
      files: null,
      // 其他表单字段...
    }}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:20:29