reactjs - 在反应中有条件地分配 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 分配给数组的一个特定元素呢?
解决方案
您不能动态分配 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 />
</>)
}
推荐阅读
- laravel - 在 Laravel 5.5 中更改查询构建器查询中的返回值
- sql-server-2008 - 仅根据单个列的重复值提取行
- java - 如何使用 ClassPathResource 从现有文件创建文件
- javascript - 如何在 jQuery CRM 动态门户中序列化查找字段
- reactjs - React VX 树状图抛出意外令牌 (125:14)
- laravel - 删除组件类只是为了使其匿名后出错
- laravel - Vue生产图像文件夹没有更新?
- c++ - 使用 C++ Boost 库在 INI 文件中使用重复的部分名称
- python - 正切方程提供错误的输出
- reactjs - 卡在后期预览组件中