使用react-hook-form上传文件后重新渲染组件

时间:2020-08-17 17:53:43

标签: reactjs react-hooks

我的申请中有

1.main component, which renders a list of items
2.button for add new item -> clicking the button opens modal with form, made with react-hook-forms (useForm)
3.this very simple form contains 2 input field - second field with folder icon for file upload
4.for file upload I have hidden input field => and in onChange method I set the file path to second input field

问题是...当我选择文件时,我的主要组件正在重新渲染。我想知道如何防止这种行为。如果您知道如何避免,请分享您的想法。 我的代码:

const SomeComponent = (props: SomeComponentProps): ReactElement<SomeComponentProps> => {
   const {register, handleSubmit} = useForm();
   const inputFile = useRef<HTMLInputElement>(null);

   const handleIconClick = (): void => {
     if(inputFile.current) {
        inputFile.current.click();
   }};

   <form onSubmit={onSubmit}>

        <input name="name"

               ref={register} />
        <input name="path"
               ref={register}

        // Hidden field for file upload
        <input type="file"
               
               ref={inputFile}
               
               style={{display: 'none'}}
               
               onChange={({target: { value }}:ChangeEvent<HTMLInputElement>): void => setValue('path', value)}
   </form>
    
         ...
   <Icon onClick={handleIconClick} ... />

         ...
}

0 个答案:

没有答案
相关问题