reactJs Formik загрузчик файлов setInitialValue из ссылки на изображение - PullRequest
0 голосов
/ 08 апреля 2020

я использую formik для своих форм в reactjs. и моя форма продукта имеет один загрузчик файлов для загрузки изображения продукта. для редактирования продукта я получаю массив путей изображения продукта. я не знаю, как показать изображения в dropzone (для отображения пользователю) из массива путей изображения. я должен установитьInitialValues ​​imagesPaths в formik.

редактировать форму продукта dropzone

<Dropzone
                    style={dropzoneStyle}
                    accept="image/*"
                    onDrop={(acceptedFiles) => {
                        // do nothing if no files
                        if (acceptedFiles.length === 0) {
                            return;
                        }

                        // on drop we add to the existing files
                        setFieldValue('Images', values.Images.concat(acceptedFiles));
                    }}
                >
                    {({ isDragActive, isDragReject, acceptedFiles, rejectedFiles }) => {
                        if (isDragActive) {
                            return 'This file is authorized';
                        }

                        if (isDragReject) {
                            return 'This file is not authorized';
                        }

                        if (values.Images.length === 0) {
                            return <p>عکس ها را بکشید و در اینجا رها کنید یا کلیک کنید</p>;
                        }

                        return values.Images.map((file, i) => <Thumb key={i} file={file} />);
                    }}
                </Dropzone>

компонент thumb

import React from "react";

export default class Thumb extends React.Component {
  state = {
    loading: false,
    thumb: undefined,
  };

  componentWillReceiveProps(nextProps) {
    if (!nextProps.file) { return; }

    this.setState({ loading: true }, () => {
      let reader = new FileReader();

      reader.onloadend = () => {
        this.setState({ loading: false, thumb: reader.result });
      };

      reader.readAsDataURL(nextProps.file);
    });
  }

  render() {
    const { file } = this.props;
    const { loading, thumb } = this.state;

    if (!file) { return null; }

    if (loading) { return <p>لطفا صبر کنید</p>; }

    return (
      <img src={thumb}
        alt={file.name}
        className="img-thumbnail mt-2"
        height={120}
        width={120} />
    );
  }
}

codeSandBox пример:

https://codesandbox.io/s/formik-multiple-upload-example-5xmp8

большое спасибо

...