Skip to content

Commit

Permalink
Fix: Class components should "consume" ref prop (#28719)
Browse files Browse the repository at this point in the history
When a ref is passed to a class component, the class instance is
attached to the ref's current property automatically. This different
from function components, where you have to do something extra to attach
a ref to an instance, like passing the ref to `useImperativeHandle`.

Existing class component code is written with the assumption that a ref
will not be passed through as a prop. For example, class components that
act as indirections often spread `this.props` onto a child component. To
maintain this expectation, we should remove the ref from the props
object ("consume" it) before passing it to lifecycle methods. Without
this change, much existing code will break because the ref will attach
to the inner component instead of the outer one.

This is not an issue for function components because we used to warn if
you passed a ref to a function component. Instead, you had to use
`forwardRef`, which also implements this "consuming" behavior.

There are a few places in the reconciler where we modify the fiber's
internal props object before passing it to userspace. The trickiest one
is class components, because the props object gets exposed in many
different places, including as a property on the class instance.

This was already accounted for when we added support for setting default
props on a lazy wrapper (i.e. `React.lazy` that resolves to a class
component).

In all of these same places, we will also need to remove the ref prop
when `enableRefAsProp` is on.

Closes #28602

---------

Co-authored-by: Jan Kassens <jan@kassens.net>

DiffTrain build for commit dc545c8.
  • Loading branch information
acdlite committed Apr 3, 2024
1 parent aac8c4d commit 8051b64
Show file tree
Hide file tree
Showing 10 changed files with 1,971 additions and 1,585 deletions.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1 +1 @@
5de8703646cdd3838cb1686f761b10c0692743aa
dc545c8d6eaca87c8d5cabfab6e1c768ecafe426
Loading

0 comments on commit 8051b64

Please sign in to comment.