我面临 ref 的问题 - 我需要引用功能组件并将 Prop 传递给它。到目前为止,我得到了我的父组件和子组件。在我的父组件中,我需要对我的 child 使用 ref。我需要在我的父组件中使用 projectSectionItem。
家长:
const projectSectionItem = useRef<HTMLDivElement>(null);
return i.showOnHP === 1 ?
<Project key={index}
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}
>
{index === 0 ?
<ScrollList>
{data.map((i, index) => { return <ScrollListItem data-index={index} key={index} ref={projectIndicator} onClick={(e: React.MouseEvent<HTMLLIElement>) => scrollToNextProject(e)} /> })}
</ScrollList>
: null}
</Project>
: null;
})}
child :
type APIProps = {
url?: string,
client?: string,
project?: string,
btn_text?: string,
btn_color?: string,
href?: string,
}
type HWWProps = {
order_client?: number,
order_project?: number,
className?: string
ref?: React.MutableRefObject<HTMLDivElement>
}
type ProjectProps = APIProps & HWWProps;
export const Project: React.FC<ProjectProps> = props => {
return (
<StyledProject className={props.className}>
<ProjectContainer>
<ProjectImage src={props.url} alt={props.client} />
<ProjectTextWrapper>
<ProjectBrand order_client={props.order_client}>{props.client}</ProjectBrand>
<ProjectName order_project={props.order_project}>{props.project}</ProjectName>
<ButtonExtend as={Button} color={props.btn_color}><Link to={props.href}>{props.btn_text}</Link></ButtonExtend>
</ProjectTextWrapper>
</ProjectContainer>
{props.children}
</StyledProject>
)
}
最佳答案
如果不使用 React.forwardRef
,则无法将引用添加到功能组件。将其传递给 HTMLDIVElement 或使用 useImperativeHandle
钩子(Hook)暴露一些功能
由于您希望在 Project 组件中添加 ref 一个 DOM 元素,您可以使用 innerRef 属性将 ref 传递给 StyledProject 组件,该组件是一个样式化组件
export const Project: React.FC<ProjectProps> = React.forwardRef((props ,ref: : Ref<HTMLDivElement>)=> {
return (
<StyledProject className={props.className} innerRef={ref}>
<ProjectContainer>
<ProjectImage src={props.url} alt={props.client} />
<ProjectTextWrapper>
<ProjectBrand order_client={props.order_client}>{props.client}</ProjectBrand>
<ProjectName order_project={props.order_project}>{props.project}</ProjectName>
<ButtonExtend as={Button} color={props.btn_color}><Link to={props.href}>{props.btn_text}</Link></ButtonExtend>
</ProjectTextWrapper>
</ProjectContainer>
{props.children}
</StyledProject>
)
});
完成此操作后,您可以像
projectSectionItem.current
一样访问父级中的 ref
关于javascript - 用 forwardedRef react FC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62132089/