Skip to content

feat: support ref parameter for Image component #373

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions src/Image.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import type { GetContainer } from 'rc-util/lib/PortalWrapper';
import useMergedState from 'rc-util/lib/hooks/useMergedState';
import * as React from 'react';
import { useContext, useMemo, useState } from 'react';
import { forwardRef, useContext, useMemo, useState } from 'react';
import type { PreviewProps, ToolbarRenderInfoType } from './Preview';
import Preview from './Preview';
import PreviewGroup from './PreviewGroup';
Expand Down Expand Up @@ -69,11 +69,14 @@
onError?: (e: React.SyntheticEvent<HTMLImageElement, Event>) => void;
}

interface CompoundedComponent<P> extends React.FC<P> {
interface CompoundedComponent<P, T> extends React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<T>> {
PreviewGroup: typeof PreviewGroup;
}

const ImageInternal: CompoundedComponent<ImageProps> = props => {
const ImageInternal = forwardRef<
HTMLImageElement,
ImageProps
>((props, ref: React.Ref<HTMLImageElement>) => {
const {
src: imgSrc,
alt,
Expand Down Expand Up @@ -206,7 +209,15 @@
height,
...style,
}}
ref={getImgRef}
ref={(img) => {
getImgRef(img);

if (typeof ref === 'function') {
ref(img);

Check warning on line 216 in src/Image.tsx

View check run for this annotation

Codecov / codecov/patch

src/Image.tsx#L216

Added line #L216 was not covered by tests
} else if (ref) {
(ref as React.MutableRefObject<HTMLImageElement>).current = img;

Check warning on line 218 in src/Image.tsx

View check run for this annotation

Codecov / codecov/patch

src/Image.tsx#L218

Added line #L218 was not covered by tests
}
}}
{...srcAndOnload}
width={width}
height={height}
Expand Down Expand Up @@ -257,7 +268,7 @@
)}
</>
);
};
}) as CompoundedComponent<ImageProps, HTMLImageElement>;

ImageInternal.PreviewGroup = PreviewGroup;

Expand Down