mirror of
https://github.com/facebook/react.git
synced 2025-11-01 09:12:30 +00:00
Merge pull request #4943 from bspaulding/throw-stateless-ref
Composite component throws on attaching ref to stateless component #4939
This commit is contained in:
@@ -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 />;
|
||||
|
||||
Reference in New Issue
Block a user