Merge pull request #4943 from bspaulding/throw-stateless-ref

Composite component throws on attaching ref to stateless component #4939
This commit is contained in:
Sebastian Markbåge
2015-10-06 14:33:48 -07:00
2 changed files with 33 additions and 1 deletions
@@ -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;
},
/**
@@ -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 <StatelessComponent name="A" ref="stateless"/>;
},
});
ReactTestUtils.renderIntoDocument(<Parent/>);
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 <div />;