如何解决有条件地在 react
我正在做一些反应,但遇到了一个我自己无法解决的挑战。我在这里和其他地方搜索过,我发现了标题相似的主题,但与我遇到的问题没有任何关系,所以我们开始:
所以我有一个数组,它将被映射到 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 动态分配给数组的一个特定元素?
解决方法
不能动态分配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 />
</>)
}
,
解决方案
就像 Drew 在 Medets answer 中评论的那样,唯一的解决方案是创建一个 refs 数组并通过简单地将 ChildElement 的索引与 ref 数组的索引相匹配来访问所需的数组,如我们所见 here .我们发现无法在对象之间实际移动引用,但这样做的性能成本应该无关紧要。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。