块编辑器开发文档

💡 云策文档标注

概述

FormFileUpload 是 WordPress 组件库中的一个 React 组件,用于实现文件上传功能,允许用户从本地设备选择文件。它提供了丰富的 Props 来自定义行为和样式。

关键要点

  • 组件导入:通过 @wordpress/components 导入 FormFileUpload。
  • 核心功能:支持文件选择,可通过 onChange 回调获取文件列表。
  • Props 配置:包括 accept(文件类型限制)、multiple(多选)、__next40pxDefaultSize(尺寸优化)等。
  • 自定义渲染:可使用 render Prop 自定义 UI,替代默认按钮。

代码示例

import { FormFileUpload } from '@wordpress/components';

const MyFormFileUpload = () => (
  <FormFileUpload
    __next40pxDefaultSize
    accept="image/*"
    onChange={ ( event ) => console.log( event.currentTarget.files ) }
  >
    Upload
  </FormFileUpload>
);

注意事项

  • onChange 是必填 Prop,用于处理文件选择事件。
  • 使用 onClick 可以强制触发 change 事件,例如通过设置 event.target.value = '' 来允许重复选择同一文件。
  • render Prop 允许完全自定义 UI,但需手动调用 openFileDialog 函数打开文件对话框。

📄 原文内容

See the WordPress Storybook for more detailed, interactive documentation.

FormFileUpload allows users to select files from their local device.

import { FormFileUpload } from '@wordpress/components';

const MyFormFileUpload = () => (
  <FormFileUpload
    __next40pxDefaultSize
    accept="image/*"
    onChange={ ( event ) => console.log( event.currentTarget.files ) }
  >
    Upload
  </FormFileUpload>
);

Props

__next40pxDefaultSize

  • Type: boolean
  • Required: No
  • Default: false

Start opting into the larger default height that will become the default size in a future version.

accept

  • Type: string
  • Required: No

A string passed to the input element that tells the browser which
file types
can be uploaded by the user. e.g: image/*,video/*.

children

  • Type: ReactNode
  • Required: No

Children are passed as children of Button.

icon

  • Type: IconType | null
  • Required: No

The icon to render in the default button.

See the Icon component docs for more information.

multiple

  • Type: boolean
  • Required: No
  • Default: false

Whether to allow multiple selection of files or not.

onChange

  • Type: ChangeEventHandler<HTMLInputElement> | undefined
  • Required: Yes

Callback function passed directly to the input file element.

Select files will be available in event.currentTarget.files.

onClick

  • Type: MouseEventHandler<HTMLInputElement>
  • Required: No

Callback function passed directly to the input file element.

This can be useful when you want to force a change event to fire when
the user chooses the same file again. To do this, set the target value to
an empty string in the onClick function.

<FormFileUpload
  __next40pxDefaultSize
  onClick={ ( event ) => ( event.target.value = '' ) }
  onChange={ onChange }
>
  Upload
</FormFileUpload>

render

  • Type: ((arg: { openFileDialog: () => void; }) => ReactNode)
  • Required: No

Optional callback function used to render the UI.

If passed, the component does not render the default UI (a button) and
calls this function to render it. The function receives an object with
property openFileDialog, a function that, when called, opens the browser
native file upload modal window.