antd表单中动态设置upload表单项的值实现编辑功能

问题描述:

编辑页面图片已上传列表未正常展示

问题出现原因

form表单中initialValue只能显示初始值(空数组),之后预期的值都无法显示

render部分

const {
    
    defaultFileList} = this.state; // defaultFileList初始值为空数组,接口返回数据后,调用setState修改defaultFileList的值为远程数据

dom部分

<Form.Item label="图片上传">
            {
    
    getFieldDecorator('imageInfoArr', {
    
    
              initialValue: defaultFileList,
            })(
              <Upload disabled={
    
    disabledState} {
    
    ...props}>
                <div className={
    
    styles.upload}>
                  <Icon type="picture" className={
    
    styles.uploadImg} />
                  <span className={
    
    styles.uploadText}>
                    上传图片的格式为(jpg、png、jpeg等常用图片格式)
                  </span>
                </div>
              </Upload>
            )}
</Form.Item>

问题解决方案

不应该使用initialValue属性实现编辑功能,而应该使用使用 fileList 对列表进行完全控制,可以实现各种自定义功能,例如读取远程路径并显示链接

import {
    
     Upload, Button } from 'antd';
import {
    
     UploadOutlined } from '@ant-design/icons';

class MyUpload extends React.Component {
    
    
  state = {
    
    
    fileList: [
      {
    
    
        uid: '-1',
        name: 'xxx.png',
        status: 'done',
        url: 'http://www.baidu.com/xxx.png',
      },
    ],
  };

  handleChange = info => {
    
    
    let fileList = [...info.fileList];

    // 1. Limit the number of uploaded files
    // Only to show two recent uploaded files, and old ones will be replaced by the new
    fileList = fileList.slice(-2);

    // 2. Read from response and show file link
    fileList = fileList.map(file => {
    
    
      if (file.response) {
    
    
        // Component will show file.url as link
        file.url = file.response.url;
      }
      return file;
    });

    this.setState({
    
     fileList });
  };

  render() {
    
    
    const props = {
    
    
      action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
      onChange: this.handleChange,
      multiple: true,
    };
    return (
      <Upload {
    
    ...props} fileList={
    
    this.state.fileList}>
        <Button>
          <UploadOutlined /> Upload
        </Button>
      </Upload>
    );
  }
}

ReactDOM.render(<MyUpload />, mountNode);

猜你喜欢

转载自blog.csdn.net/tianxintiandisheng/article/details/108086934