我正在做一些反应,并遇到了一个我无法解决自己的挑战。我在这里和其他地方搜索过,找到了标题相似的主题,但与我遇到的问题没有任何关系,所以我们开始:
所以我有一个数组,它将被映射到 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}>})}
</>)
}
但问题是,父元素中有一个状态,它存储当前选定的子组件之一的 id(我通过设置上下文并在子组件内设置此状态来做到这一点),然后问题是我必须引用当前选定的 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 />
</>)
}
但我已经尝试过了,但我们做不到。那么,如果某一条件为真,如何动态地将 ref 分配给数组的一个特定元素呢?
您可以使用 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 />
)
}
你不能动态分配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 />
</>)
}
事实上,动态指定一个ref是可行的。 React 为此提供了 MutableRefObject 类型。
//...
const selectedRef = useRef<HTMLButtonElement | null>(null)
const handleClick = (e: React.MouseEvent) => {
selectedRef.current = e.currentTarget as HTMLButtonElement
}
//...
就像 Drew 在 Medets 答案中评论的那样,唯一的解决方案是创建一个 ref 数组,并通过简单地将 ChildElement 的索引与 ref 数组的索引相匹配来访问所需的数组,正如我们在here中看到的那样。我们发现无法在对象之间实际移动引用,但这样做的性能成本应该不相关。