首页 > 解决方案 > 在反应中有条件地分配 ref

问题描述

我正在做一些反应,遇到了一个我自己无法解决的挑战。我在这里和其他地方搜索过,我发现了类似标题的主题,但与我遇到的问题没有任何关系,所以我们开始吧:

所以我有一个数组,它将被映射到 React 组件中,通常如下所示:

export default ParentComponent = () => {

//bunch of stuff here and there is an array called arr

return (<>
 
    {arr.map((item, id) => {<ChildComponent props={item} key={id}>})}

</>)

}

但问题是,父元素中有一个状态,它存储当前选择的其中一个 ChildComponents 的 id(我通过设置上下文并在 ChildComponent 中设置此状态来做到这一点),然后问题是我必须引用当前选择的 ChildComponent 内部的一个节点。我可以转发 ref 没问题,但我也想只在当前选择的 ChildComponent 上分配 ref,我想这样做:

export default ParentComponent = () => {

//bunch of stuff here and there is an array called arr and there's a state which holds the id of a  selected ChildComponent called selectedObjectId

const selectedRef = createRef();

return (<>
    <someContextProvider>
    {arr.map((item, id) => {
       <ChildComponent 
        props={item} 
        key={id} 
        ref={selectedObjectId == id ? selectedRef : null}
       >
    })}
   <someContextProvider />
</>)

}

但我试过了,我们做不到。那么,如果某个条件为真,如何动态地将 ref 分配给数组的一个特定元素呢?

标签: reactjsreact-hooksreact-ref

解决方案


您不能动态分配 ref,但您可以存储所有这些,并通过 id 访问

export default ParentComponent = () => {

//bunch of stuff here and there is an array called arr and theres a state wich holds the id of a  selected ChildComponent called selectedObjectId


let refs = {}

// example of accessing current selected ref
const handleClick = () => {
    if (refs[selectedObjectId])
        refs[selectedObjectId].current.click() // call some method
}

return (<>
    <someContextProvider>
    {arr.map((item, id) => {
       <ChildComponent 
        props={item} 
        key={id} 
        ref={refs[id]}
       >
    })}
   <someContextProvider />
</>)

}

推荐阅读