首页 > 解决方案 > 组件列表:函数没有收到正确的参数

问题描述

我有一个相同组件的列表(用于呈现自定义文件类型输入),如下所示:

         <CustomInput
            fileName={filesNames[1]}
            inputChangeFunction={handlingFileChange}
            index={1}
          />
          <CustomInput
            fileName={filesNames[2]}
            inputChangeFunction={handlingFileChange}
            index={2}
          />
          <CustomInput
            fileName={filesNames[3]}
            inputChangeFunction={handlingFileChange}
            index={3}
          />

这个组件是这样构建的:

export default function CustomInput({
  fileName,
  inputChangeFunction,
  index,
}) {
  return (
    <label htmlFor="realInput" className="customInputLabel">
      <CustomButton/>
      <p>{fileName || "pick a file"}</p>
      <input
        type="file"
        id="realInput"
        name="realInput"
        style={{ display: "none" }}
        onChange={(e) => {inputChangeFunction(e, index)}}
      />
    </label>
  );
}

当要上传的文件被修改时,会调用这个回调函数:

  const handlingFileChange = (e, index) => {
    console.log("input : ", e.target, index);
    let stockSizes = filesSizes;
    let stockNames = filesNames;
    let stockSum = 0;
    if (stockSizes.length === index) {
      stockSizes.push(e.target.files[0].size);
      stockNames.push(e.target.value);
    } else {
      stockSizes.splice(index, 1, e.target.files[0].size);
      stockNames.splice(index, 1, e.target.value);
    }
    setFilesSizes(stockSizes);
    setFilesNames(stockNames);
    for (let i = 0; i < stockSizes.length; i++) {
      stockSum = stockSum + stockSizes[i];
    }
    setSizesSum(stockSum);
    console.log("names : ", filesNames);
    console.log("sizes : ", filesSizes);
    if (filesSizes.length === filesCounter) {
      handlingFilesCounter("adding");
    }
  };

这是我的问题:每当我单击这三个组件中的一个时,该函数总是从第一个组件接收道具 (filesNames[1], 1)...而且我不知道为什么!

标签: javascriptreactjs

解决方案


推荐阅读