Skip to content

Commit 1081a9d

Browse files
committed
fix: ref logic
1 parent 2c6d3bc commit 1081a9d

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

src/Immutable.tsx

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,18 +28,20 @@ export function makeImmutable<T extends React.ComponentType<any>>(Component: T):
2828
export function responseImmutable<T extends React.ComponentType<any>>(Component: T): T {
2929
const refAble = supportRef(Component);
3030

31-
const ImmutableComponent = React.memo(function (props: any, ref: any) {
31+
const ImmutableComponent = function (props: any, ref: any) {
3232
const refProps = refAble ? { ref } : {};
3333
React.useContext(RenderContext);
3434

3535
return <Component {...props} {...refProps} />;
36-
});
36+
};
3737

3838
if (process.env.NODE_ENV !== 'production') {
3939
ImmutableComponent.displayName = `ImmutableResponse(${
4040
Component.displayName || Component.name
4141
})`;
4242
}
4343

44-
return refAble ? React.forwardRef(ImmutableComponent) : (ImmutableComponent as any);
44+
return refAble
45+
? React.memo(React.forwardRef(ImmutableComponent))
46+
: (React.memo(ImmutableComponent) as any);
4547
}

tests/immutable.test.tsx

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,4 +74,25 @@ describe('Immutable', () => {
7474
expect(container.querySelector('#value')!.textContent).toEqual('1');
7575
});
7676
});
77+
78+
it('ref-able', () => {
79+
const Root = React.forwardRef<HTMLDivElement, { children?: React.ReactNode }>((_, ref) => (
80+
<div className="root" ref={ref} />
81+
));
82+
const ImmutableRoot = makeImmutable(Root);
83+
const Raw = React.forwardRef<HTMLDivElement>((_, ref) => <div className="raw" ref={ref} />);
84+
const ImmutableRaw = responseImmutable(Raw);
85+
86+
const rootRef = React.createRef<HTMLDivElement>();
87+
const rawRef = React.createRef<HTMLDivElement>();
88+
89+
const { container } = render(
90+
<ImmutableRoot ref={rootRef}>
91+
<ImmutableRaw ref={rawRef} />
92+
</ImmutableRoot>,
93+
);
94+
95+
expect(rootRef.current).toBe(container.querySelector('.root'));
96+
expect(rawRef.current).toBe(container.querySelector('.raw'));
97+
});
7798
});

0 commit comments

Comments
 (0)