当传递给函数时,React在map中发送最后一个元素



我试图使用react创建动态UI元素,并通过映射数组创建元素循环,并单击元素,它将值传递给函数。我的代码看起来像下面的

const [shortlistedIds, setShortlistedIds] = useState([]);
const attachmentInputRef = useRef();
const handleOpenFilePicker = async () => {
attachmentInputRef.current.click();
};
//somewhere in code, set the IDs
setShortlistedIds(["1", "2", "3", "4"]);
const handleFilePicker = async(e) => {
console.log(e.target.id)
let uploadFiles = [...e.target.files]
const apiRes = await api.createAttachment(e.target.id, uploadFiles)
}
return(
{shortlistedIds.map((myId) => (
<button
id={myId}
className="attachment-button pull-right"                 
onClick={handleOpenFilePicker}
style={{ position: "absolute" }}
>
click me {myId}
</button>
<input
id={myId}
ref={attachmentInputRef}
type="file"
style={{ display: "none" }}
name="file"
onChange={(e) => {handleFilePickerChange(myId, e);}}
multiple
/>
)
)};
)

html是正确呈现的,每个按钮都有正确的id和文本,但在单击时,从handleFilePicker打印到控制台的值始终是最后一个id, "4"从上面的例子,不管我点击哪个按钮。不知道这里有什么问题。(请忽略任何错别字,因为这是基于实际代码的示例代码。在这里粘贴实际代码是不可行的)

简单点

const [shortlistedIds, setShortlistedIds] = useState([]);
useEffect(() => {
setShortlistedIds(["1", "2", "3", "4"]);
}, [])
const targetClick = (e)=>{
console.log(e);
}

return (
{
shortlistedIds.map(myId => {
return(<button onClick={() =>targetClick(myId)} key={myId}>click me{myId}</button>)

})
}
)

上面的问题是useRef()指向一个引用,因此,每次在映射中分配它时,重新分配它都会改变值,最终分配给最终值。useRef()钩子不会在输入字段的每个赋值中复制。

为了解决这个问题,我将输入块移动到一个子组件,该组件为每个输入字段创建了一个useRef()钩子,因此工作良好。

您必须在按钮元素中传递属性key={myid}。

最新更新