我面临的问题,参考-我需要参考功能组件和传递道具到它。到目前为止,我已经得到了我的父组件和子组件。在我的父组件中,我需要对我的子组件使用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;
})}儿童:
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>
)
}发布于 2020-06-01 13:11:15
在不使用React.forwardRef将其传递给HTMLDIVElement或使用useImperativeHandle钩子公开某些函数的情况下,不能向functional添加推荐。
由于您希望在Project中添加一个DOM元素,所以可以将ref传递给StyledProject组件,该组件是一个样式化的组件,可以使用innerRef支柱
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。
https://stackoverflow.com/questions/62132089
复制相似问题