javascript - 如何引用地图内的多个组件
问题描述
我需要为 map 函数中的每个项目设置 ref。我正在将孩子的参考转发给我的父母,目前我只有一个项目。我需要将 refs 设置为数组列表,然后使用它。我试过这样的事情:
const projectSectionItem = useRef([])
ref={projectSectionItem => projectSectionItem[index] = projectSectionItem}
家长:
const projectSectionItem = useRef<HTMLDivElement>(null)
<StyledSection ref={projectSection}>
{data.map((i, index) => {
return i.showOnHP === 1 ?
<Element name={index.toString()} key={index}>
<Project
url={`${URL}${i.button_image.image}`}
client={i.client_name}
project={i.project.en}
btn_color={"#000"}
btn_text={i.button_text}
href={`/cases/${i.slug}`}
ref={projectSectionItem}
>
</Project>
</Element>
: null
})}
孩子:
export const Project = React.forwardRef<HTMLDivElement, ProjectProps>((props, ref) => {
return (
<StyledProject className={props.className} ref={ref}>
...
</StyledProject>
)
})
解决方案
由于您不应该在循环中或有条件地使用钩子(useRef),您可以createRef
像这样使用:
const pressureRefs = data.filter(item => item.showOnHP).map(() => React.createRef<HTMLDivElement>())
<Project ... ref={refs[i]} />
推荐阅读
- node.js - Node-SQLite3 In-Memory-DB:从文件初始化并写回文件
- struct - 初始化后可以向结构添加新字段吗?
- python - 生成器的Python生成器
- splunk - splunk 仪表板中缺少几个小时的事件
- javascript - 假计时器在 Jest 中无法正确触发 setTimeout 调用
- python - 我可以将 len(game_content) 用于我的 while 条件吗?
- android - 如何从 firebase 获取数据到数据模型?
- r - 使用分组的 dplyr 标识符查找 2 个数据帧之间最接近的匹配数
- python-3.x - 机器学习模型,它获取数据集并创建一个线性回归模型,该模型给出基于用户响应的答案
- c++ - 在 OS X 上使用 c++ 链接问题