UNPKG

2.44 kBJavaScriptView Raw
1/**
2 * Copyright (c) 2013-present, Facebook, Inc.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 *
8 */
9
10'use strict';
11
12var ReactOwner = require('./ReactOwner');
13
14var ReactRef = {};
15
16function attachRef(ref, component, owner) {
17 if (typeof ref === 'function') {
18 ref(component.getPublicInstance());
19 } else {
20 // Legacy ref
21 ReactOwner.addComponentAsRefTo(component, ref, owner);
22 }
23}
24
25function detachRef(ref, component, owner) {
26 if (typeof ref === 'function') {
27 ref(null);
28 } else {
29 // Legacy ref
30 ReactOwner.removeComponentAsRefFrom(component, ref, owner);
31 }
32}
33
34ReactRef.attachRefs = function (instance, element) {
35 if (element === null || typeof element !== 'object') {
36 return;
37 }
38 var ref = element.ref;
39 if (ref != null) {
40 attachRef(ref, instance, element._owner);
41 }
42};
43
44ReactRef.shouldUpdateRefs = function (prevElement, nextElement) {
45 // If either the owner or a `ref` has changed, make sure the newest owner
46 // has stored a reference to `this`, and the previous owner (if different)
47 // has forgotten the reference to `this`. We use the element instead
48 // of the public this.props because the post processing cannot determine
49 // a ref. The ref conceptually lives on the element.
50
51 // TODO: Should this even be possible? The owner cannot change because
52 // it's forbidden by shouldUpdateReactComponent. The ref can change
53 // if you swap the keys of but not the refs. Reconsider where this check
54 // is made. It probably belongs where the key checking and
55 // instantiateReactComponent is done.
56
57 var prevRef = null;
58 var prevOwner = null;
59 if (prevElement !== null && typeof prevElement === 'object') {
60 prevRef = prevElement.ref;
61 prevOwner = prevElement._owner;
62 }
63
64 var nextRef = null;
65 var nextOwner = null;
66 if (nextElement !== null && typeof nextElement === 'object') {
67 nextRef = nextElement.ref;
68 nextOwner = nextElement._owner;
69 }
70
71 return prevRef !== nextRef ||
72 // If owner changes but we have an unchanged function ref, don't update refs
73 typeof nextRef === 'string' && nextOwner !== prevOwner;
74};
75
76ReactRef.detachRefs = function (instance, element) {
77 if (element === null || typeof element !== 'object') {
78 return;
79 }
80 var ref = element.ref;
81 if (ref != null) {
82 detachRef(ref, instance, element._owner);
83 }
84};
85
86module.exports = ReactRef;
\No newline at end of file