首页 > 解决方案 > 如何引用地图内的多个组件

问题描述

我需要为 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>
    )

})

标签: javascriptreactjstypescript

解决方案


由于您不应该在循环中或有条件地使用钩子(useRef),您可以createRef像这样使用:

const pressureRefs = data.filter(item => item.showOnHP).map(() => React.createRef<HTMLDivElement>())
<Project ... ref={refs[i]} /> 

推荐阅读