简体   繁体   English

将 forwardRef 与 Link 组件一起使用

[英]Using forwardRef with a Link component

I need use use forwardRef to forward a ref to a child component.我需要使用forwardRef将 ref 转发到子组件。 The below works fine, but ideally I would not rely on a div element to wrap the link, as it makes styling the link awkward.下面的工作正常,但理想情况下我不会依赖 div 元素来包装链接,因为它使链接样式变得笨拙。

const RoleCard = forwardRef((props, innerRef) => {
    return (
        <div ref={innerRef} className="RoleCard" key={props.role.id}>
            <Link
                to={{
                    pathname: `roles/${props.role.slug}`
                }}
            >
                <div className="RoleCard__Inner">
                    <span className="RoleCard__Title">{props.role.title}</span>
                    <div className="RoleCard__Body">
                        {props.role.description}
                    </div>
                </div>
            </Link>
        </div>
    );
});

However, the below doesn't work, as the ref is not forwarded (because Link is actually a HOC?).但是,下面不起作用,因为引用没有转发(因为链接实际上是一个 HOC?)。

Is it possible to pass the innerRef through the Link?是否可以通过链接传递innerRef

const RoleCard = forwardRef((props, innerRef) => {
    return (
        <Link
            ref={innerRef}
            className="RoleCard"
            key={props.role.id}>
            to={{
                pathname: `roles/${props.role.slug}`
            }}
        >
            <div className="RoleCard__Inner">
                <span className="RoleCard__Title">{props.role.title}</span>
                <div className="RoleCard__Body">
                    {props.role.description}
                </div>
            </div>
        </Link>
    );
});

The Link component has a innerRef prop that you can use to pass a ref to the element rendered by the component. Link组件有一个innerRef ,您可以使用它来将 ref 传递给组件呈现的元素。

const RoleCard = forwardRef((props, innerRef) => {
  return (
    <Link
      innerRef={innerRef}
      className="RoleCard"
      key={props.role.id}
      to={{
        pathname: `roles/${props.role.slug}`
      }}
    >
      <div className="RoleCard__Inner">
        <span className="RoleCard__Title">{props.role.title}</span>
        <div className="RoleCard__Body">{props.role.description}</div>
      </div>
    </Link>
  );
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM