简体   繁体   English

如何在for循环中设置react ref

[英]How to set react ref in a for loop

I have a 'fileUpload' component which I am passing into a form in my React App.我有一个“fileUpload”组件,我将它传递到我的 React 应用程序中的表单中。

I want to have the ability to set a unique ref for each input element in my for loop and then pass this ref to a delete button to remove the file.我希望能够为我的 for 循环中的每个输入元素设置一个唯一的引用,然后将此引用传递给删除按钮以删除文件。

FileUploadComponent文件上传组件

const FileUpload = ({ addFile, runClick }) => {
          const uploadButton = [];
          const myRefs = React.useRef([]);
        
          for (let i = 1; i < 6; i += 1) {
            uploadButton.push(
              <div key={i}>
                <input
                  type="file"
                  id={`file${i}`}
                  ref={myRefs.current[i] ?? React.createRef()}
                  name={`file${i}`}
                  onChange={addFile}
                />
                <RemoveButton type="button" onClick={() => removeFile()}>
                  X button{i}
                </RemoveButton>
              </div>
            );
          }
    
      return uploadButton;
    };
    
    export default FileUpload;

FormComponent表单组件

//working without using the FileUploadComponent and setting/passing the ref manually //在不使用 FileUploadComponent 和手动设置/传递 ref 的情况下工作

<InputField className="col">
        <input
          type="file"
          id="file3"
          name="file3"
          ref={ref3}
          onChange={addFile}
        />
        <RemoveButton type="button" onClick={() => removeFile(ref3)}>
          X
        </RemoveButton>
      </InputField>

// trying to have the ref be automatically assigned and passed to delete button // 尝试自动分配 ref 并传递给删除按钮

<InputField className="col">
    <FileUpload addFile={addFile} runClick={() => removeFile()} />
  </InputField>

You can create an array of refs before the loop, using Array.fill() :您可以使用Array.fill()在循环之前创建一个引用数组:

const myRefs = useRef(new Array(6).fill(createRef()));

And use it in the loop like:并在循环中使用它,如:

<input type="file" ref={myRefs[i]}/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM