在react中有条件地分配ref

Dan*_*des 8 reactjs react-ref react-hooks

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

所以我有一个数组,它将被映射到 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}>})}

</>)

}
Run Code Online (Sandbox Code Playgroud)

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

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 />
</>)

}
Run Code Online (Sandbox Code Playgroud)

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

phd*_*ign 12

您可以使用 props spread 运算符{...props}通过首先构建 props 对象来传递条件引用。例如

export default ParentComponent = () => {
  const selectedRef = useRef(null);

  return (
    <SomeContextProvider>
      {arr.map((item, id) => {
        const itemProps = selectedObjectId == id ? { ref: selectedRef } : {};
        return ( 
          <ChildComponent 
            props={item} 
            key={id} 
            {...itemProps}
          />
        );
      })}
    <SomeContextProvider />
  )
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*des -1

解决方案

就像 Drew 在 Medets 答案中评论的那样,唯一的解决方案是创建一个 ref 数组,并通过简单地将 ChildElement 的索引与 ref 数组的索引相匹配来访问所需的数组,正如我们在此处看到的那样。我们发现无法在对象之间实际移动引用,但这样做的性能成本应该不相关。