Skip to content
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

[RFC] Add a new React.createRef() API for ref objects #11555

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 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
47 changes: 46 additions & 1 deletion packages/react-dom/src/__tests__/ReactComponent-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ describe('ReactComponent', () => {
ReactTestUtils.renderIntoDocument(<Parent child={<span />} />);
});

it('should support new-style refs', () => {
it('should support callback-style refs', () => {
var innerObj = {};
var outerObj = {};

Expand Down Expand Up @@ -185,6 +185,51 @@ describe('ReactComponent', () => {
expect(mounted).toBe(true);
});

it('should support object-style refs', () => {
var innerObj = {};
var outerObj = {};

class Wrapper extends React.Component {
getObject = () => {
return this.props.object;
};

render() {
return <div>{this.props.children}</div>;
}
}

var mounted = false;

class Component extends React.Component {
constructor() {
super();
this.innerRef = React.createRef();
this.outerRef = React.createRef();
}
render() {
var inner = (
<Wrapper object={innerObj} ref={this.innerRef} />
);
var outer = (
<Wrapper object={outerObj} ref={this.outerRef}>
{inner}
</Wrapper>
);
return outer;
}

componentDidMount() {
expect(this.innerRef.contents.getObject()).toEqual(innerObj);
expect(this.outerRef.contents.getObject()).toEqual(outerObj);
mounted = true;
}
}

ReactTestUtils.renderIntoDocument(<Component />);
expect(mounted).toBe(true);
});

it('should support new-style refs with mixed-up owners', () => {
class Wrapper extends React.Component {
getTitle = () => {
Expand Down
42 changes: 41 additions & 1 deletion packages/react-dom/src/__tests__/ReactErrorBoundaries-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -937,7 +937,7 @@ describe('ReactErrorBoundaries', () => {
expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
});

it('resets refs if mounting aborts', () => {
it('resets callback refs if mounting aborts', () => {
function childRef(x) {
log.push('Child ref is set to ' + x);
}
Expand Down Expand Up @@ -981,6 +981,46 @@ describe('ReactErrorBoundaries', () => {
]);
});

it('resets object refs if mounting aborts', () => {
let childRef = React.createRef();
let errorMessageRef = React.createRef();

var container = document.createElement('div');
ReactDOM.render(
<ErrorBoundary errorMessageRef={errorMessageRef}>
<div ref={childRef} />
<BrokenRender />
</ErrorBoundary>,
container,
);
expect(container.textContent).toBe('Caught an error: Hello.');
expect(log).toEqual([
'ErrorBoundary constructor',
'ErrorBoundary componentWillMount',
'ErrorBoundary render success',
'BrokenRender constructor',
'BrokenRender componentWillMount',
'BrokenRender render [!]',
// Handle error:
// Finish mounting with null children
'ErrorBoundary componentDidMount',
// Handle the error
'ErrorBoundary componentDidCatch',
// Render the error message
'ErrorBoundary componentWillUpdate',
'ErrorBoundary render error',
'ErrorBoundary componentDidUpdate',
]);
expect(errorMessageRef.contents.toString()).toEqual('[object HTMLDivElement]');

log.length = 0;
ReactDOM.unmountComponentAtNode(container);
expect(log).toEqual([
'ErrorBoundary componentWillUnmount',
]);
expect(errorMessageRef.contents).toEqual(null);
});

it('successfully mounts if no error occurs', () => {
var container = document.createElement('div');
ReactDOM.render(
Expand Down
2 changes: 1 addition & 1 deletion packages/react-reconciler/src/ReactChildFiber.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ function getIteratorFn(maybeIterable: ?any): ?() => ?Iterator<*> {

function coerceRef(current: Fiber | null, element: ReactElement) {
let mixedRef = element.ref;
if (mixedRef !== null && typeof mixedRef !== 'function') {
if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
if (element._owner) {
const owner: ?Fiber = (element._owner: any);
let inst;
Expand Down
3 changes: 2 additions & 1 deletion packages/react-reconciler/src/ReactFiber.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import type {ReactElement, Source} from 'shared/ReactElementType';
import type {
RefObject,
ReactCall,
ReactFragment,
ReactPortal,
Expand Down Expand Up @@ -95,7 +96,7 @@ export type Fiber = {|

// The ref last used to attach this node.
// I'll avoid adding an owner field for prod and model that as functions.
ref: null | (((handle: mixed) => void) & {_stringRef: ?string}),
ref: null | (((handle: mixed) => void) & {_stringRef: ?string}) | RefObject,

// Input is the data coming into process this fiber. Arguments. Props.
pendingProps: any, // This type will be more specific once we overload the tag.
Expand Down
40 changes: 27 additions & 13 deletions packages/react-reconciler/src/ReactFiberCommitWork.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,18 +73,22 @@ export default function<T, P, I, TI, HI, PI, C, CC, CX, PL>(
function safelyDetachRef(current: Fiber) {
const ref = current.ref;
if (ref !== null) {
if (__DEV__) {
invokeGuardedCallback(null, ref, null, null);
if (hasCaughtError()) {
const refError = clearCaughtError();
captureError(current, refError);
if (typeof ref === "function") {
if (__DEV__) {
invokeGuardedCallback(null, ref, null, null);
if (hasCaughtError()) {
const refError = clearCaughtError();
captureError(current, refError);
}
} else {
try {
ref(null);
} catch (refError) {
captureError(current, refError);
}
}
} else {
try {
ref(null);
} catch (refError) {
captureError(current, refError);
}
ref.contents = null;
}
}
}
Expand Down Expand Up @@ -162,20 +166,30 @@ export default function<T, P, I, TI, HI, PI, C, CC, CX, PL>(
const ref = finishedWork.ref;
if (ref !== null) {
const instance = finishedWork.stateNode;
let instanceToUse;
switch (finishedWork.tag) {
case HostComponent:
ref(getPublicInstance(instance));
instanceToUse = getPublicInstance(instance);
break;
default:
ref(instance);
instanceToUse = instance;
}
if (typeof ref === 'function') {
ref(instanceToUse);
} else {
ref.contents = instanceToUse;
}
}
}

function commitDetachRef(current: Fiber) {
const currentRef = current.ref;
if (currentRef !== null) {
currentRef(null);
if (typeof currentRef === 'function') {
currentRef(null);
} else {
currentRef.contents = null;
}
}
}

Expand Down
4 changes: 3 additions & 1 deletion packages/react/src/React.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import assign from 'object-assign';
import ReactVersion from 'shared/ReactVersion';
import {enableReactFragment} from 'shared/ReactFeatureFlags';

import {createRef} from './ReactCreateRef';
import {Component, PureComponent, AsyncComponent} from './ReactBaseClasses';
import {forEach, map, count, toArray, only} from './ReactChildren';
import ReactCurrentOwner from './ReactCurrentOwner';
Expand All @@ -31,7 +32,7 @@ const REACT_FRAGMENT_TYPE =
Symbol.for('react.fragment')) ||
0xeacb;

var React = {
const React = {
Children: {
map,
forEach,
Expand All @@ -40,6 +41,7 @@ var React = {
only,
},

createRef,
Component,
PureComponent,
unstable_AsyncComponent: AsyncComponent,
Expand Down
18 changes: 18 additions & 0 deletions packages/react/src/ReactCreateRef.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing @flow annotation?


import type {RefObject} from 'shared/ReactTypes';

export function createRef(): RefObject {
const refObject = {
contents: null,
};
if (__DEV__) {
Object.seal(refObject);
}
return refObject;
}
5 changes: 5 additions & 0 deletions packages/shared/ReactTypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,8 @@ export type ReactPortal = {
// TODO: figure out the API for cross-renderer implementation.
implementation: any,
};

export type RefObject = {
contents: any,
Copy link
Contributor Author

@trueadm trueadm Nov 14, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How can we better type this so it's not any?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It can be generic

export type RefObject<T> = {
  contents: T | null
};

};