javascript - 组件列表:函数没有收到正确的参数
问题描述
我有一个相同组件的列表(用于呈现自定义文件类型输入),如下所示:
<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)...而且我不知道为什么!
解决方案
推荐阅读
- python - 获取 pandas 合并中保留列的行索引
- autohotkey - 如何通过自动热键更改资源管理器上的分组模式
- bash - 传递和解析文件匹配
- javascript - 如何在 Firebase 中获取路径
- ansible - Ansible 模块 amazon.aws 和 aws_service_ip_ranges 查找插件
- javascript - 确保用户在 React 应用程序中触发事件之前允许麦克风访问
- django - 我在使用 nginx 在同一域上设置 api 和前端时遇到问题
- amazon-web-services - Terraform:如何创建一个 S3 存储桶,其中的对象包含代码执行时间的时间戳?
- css - 在 react 中运行 yarn build 后 CSS 更改
- php - 如何使标签页标题动态化