programing

입력 유형=파일이 반응 구성 요소에서 동일한 파일을 선택하도록 허용하는 방법

newnotes 2023. 3. 16. 21:49
반응형

입력 유형=파일이 반응 구성 요소에서 동일한 파일을 선택하도록 허용하는 방법

제겐 반응 컴포넌트가 있어서<input type="file">사용자가 브라우저에서 이미지를 선택할 수 있도록 합니다.같은 파일을 선택해도 onChange 메서드가 호출되지 않습니다.몇 가지 검색 후, 누군가가 사용하라고 제안합니다.this.value=null또는return falseonChange 메서드가 종료되었을 때 사용해보았지만 동작하지 않습니다.

다음은 내 코드입니다.

<input id="upload" ref="upload" type="file" accept="image/*"
           onChange={(event)=> { this.readFile(event) }}/>

다음은 제가 시도한 것입니다.

<input id="upload" ref="upload" type="file" accept="image/*"
               onChange={(event)=> { 
                   this.readFile(event) 
                   return false
              }}/>

또 다른 예는 다음과 같습니다.

<input id="upload" ref="upload" type="file" accept="image/*"
           onChange={(event)=> { 
               this.readFile(event) 
               this.value=null
          }}/>

나는 위의 솔루션이 jquery에 효과가 있다고 믿지만 reactjs에서 어떻게 작동하게 해야 할지 모르겠다.

스레드의 Dup

<input id="upload" ref="upload" type="file" accept="image/*"
           onChange={(event)=> { 
               this.readFile(event) 
          }}
        onClick={(event)=> { 
               event.target.value = null
          }}

/>

생각합니다this당신의 기능에서는,input필드. 사용해보십시오.event.target대신.

<input id="upload" ref="upload" type="file" accept="image/*"
           onChange={(event)=> { 
               this.readFile(event) 
               event.target.value=null
          }}/>

실제 작업한 경우: event.currentTarget.value = null

    onClick={(event)=> { 
               event.currentTarget.value = null
          }}

My React 버전: 16.2.0

@jbsmoove 솔루션은 IE11을 제외한 모든 브라우저에서 정상적으로 작동합니다.

IE11의 경우, 파일을 열고 두 번째로 파일을 열 때 Cancel insteed of Open file을 클릭합니다.

정의되지 않았거나 null 참조의 속성 'name'을 가져올 수 없습니다.

그래서 IE11에서도 완벽하게 동작하는 다른 솔루션을 생각해냈습니다.

<input id="upload" ref="upload" type="file" accept="image/*"
      onInput={(event)=> { 
           this.readFile(event) 
      }}
      onClick={(event)=> { 
           event.target.value = null
      }}
/>

onChange 대신 onInput을 사용합니다.

몇 시간 동안 온라인 조사를 통해 ME의 Reactjs에 도움이 되었습니다.

<input id="upload" ref="upload" type="file" accept="image/*"
           onChange={(event)=> { 
               //to do
          }}
        onClick={(e)=> { 
               e.target.value = null
          }}

/>

아래가 저의 해결책입니다.(타이프 스크립트 사용)

import * as React from "react";

export class FileSelector extends React.Component<undefined, undefined>
{
    constructor(props: any)
    {
        super(props);
        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(selectorFiles: FileList)
    {
        console.log(selectorFiles);
    }

    render ()
    {
        return <div>
            <input type="file" onChange={ (e) => this.handleChange(e.target.files) } />
        </div>;
    }
}

같은 이미지를 선택하려면 폴백 온클릭 방법을 사용합니다.예:

  <input
    id="upload" 
    ref="upload" 
    type="file" 
    accept="image/*"       
    multiple="false"
    onChange={(e) => this.getDailyImage(e)}
    onClick={(e) => e.target.files[0] && this.getDailyImage(e)}
  />

저는 그냥...key선택 항목 사이에 기본 DOM 노드를 재설정하기 위한 입력 지원(변경 핸들러 또는 업로드/처리 상태 플래그에서 일부 증분 UID 카운터 사용):

const UploadInput = (props) => {
  const [isUploading, setUploading] = useState(false);

  const handleChange = useCallback((async (e) => {
    setUploading(true); // or setUID((old) => old + 1);

    try {
      await ... // handle processing here
    } finally {
      setUploading(false);
    }
  }, [...]);

  return (
    <div className={...}>
      <input key={isUploading} type="file" onChange={handleChange} {...props} />

      {isUploading && <Spinner />}
    </div>
  );
};

또 다른 방법으로는ref형태와 용도의formRef.reset()After processing (파일 처리 후 양식 내용을 원하지 않을 경우 제외)

나는 다음 사항을 추가하여 내 일을 시켰다.onchange이벤트 청취자inputTypescript 를 사용합니다.

const onInputFileChange = (
  event: ChangeEvent<HTMLInputElement>
): void => {
  const nativeEvent = event.nativeEvent.target as HTMLInputElement;
  const targetEvent = event.target as HTMLInputElement;
  if (targetEvent.files && targetEvent.files[0]) {
    const imageFile = targetEvent.files[0];
    // eslint-disable-next-line no-param-reassign
    nativeEvent.value = "";
  }
};

여러 파일을 사용하여 업로드하는 경우 currentTarget.value를 사용해 보십시오.

  <input id='uploadFile' type="file" onClick={(e)=> {e.currentTarget.value = null}}  onChange={onChangeGetFilesSelected}  multiple={true} accept=".xlsx,.xls,.doc, .docx,.ppt, .pptx,.txt,.pdf"/>

언급URL : https://stackoverflow.com/questions/39484895/how-to-allow-input-type-file-to-select-the-same-file-in-react-component

반응형