diff --git a/src/renderers/shared/reconciler/ReactCompositeComponent.js b/src/renderers/shared/reconciler/ReactCompositeComponent.js index 09be6c0532acb..fb570f7fe3d62 100644 --- a/src/renderers/shared/reconciler/ReactCompositeComponent.js +++ b/src/renderers/shared/reconciler/ReactCompositeComponent.js @@ -808,8 +808,21 @@ var ReactCompositeComponentMixin = { attachRef: function(ref, component) { var inst = this.getPublicInstance(); invariant(inst != null, 'Stateless function components cannot have refs.'); + var publicComponentInstance = component.getPublicInstance(); + if (__DEV__) { + var componentName = component && component.getName ? + component.getName() : 'a component'; + warning(publicComponentInstance != null, + 'Stateless function components cannot be given refs ' + + '(See ref "%s" in %s created by %s). ' + + 'Attempts to access this ref will fail.', + ref, + componentName, + this.getName() + ); + } var refs = inst.refs === emptyObject ? (inst.refs = {}) : inst.refs; - refs[ref] = component.getPublicInstance(); + refs[ref] = publicComponentInstance; }, /** diff --git a/src/renderers/shared/reconciler/__tests__/ReactStatelessComponent-test.js b/src/renderers/shared/reconciler/__tests__/ReactStatelessComponent-test.js index c94c60f8274b3..3f703b3cd4fa1 100644 --- a/src/renderers/shared/reconciler/__tests__/ReactStatelessComponent-test.js +++ b/src/renderers/shared/reconciler/__tests__/ReactStatelessComponent-test.js @@ -125,6 +125,25 @@ describe('ReactStatelessComponent', function() { ); }); + it('should warn when given a ref', function() { + spyOn(console, 'error'); + + var Parent = React.createClass({ + displayName: 'Parent', + render: function() { + return ; + }, + }); + ReactTestUtils.renderIntoDocument(); + + expect(console.error.argsForCall.length).toBe(1); + expect(console.error.argsForCall[0][0]).toContain( + 'Stateless function components cannot be given refs ' + + '(See ref "stateless" in StatelessComponent created by Parent). ' + + 'Attempts to access this ref will fail.' + ); + }); + it('should provide a null ref', function() { function Child() { return
;