Fix cloneWithProps() to allow overriding props

This is a clear bug.
This commit is contained in:
Pete Hunt
2014-02-04 14:37:53 -08:00
committed by Paul O’Shannessy
parent 945f788a41
commit 9730759322
2 changed files with 21 additions and 26 deletions
+15 -2
View File
@@ -55,7 +55,7 @@ describe('cloneWithProps', function() {
});
var component = ReactTestUtils.renderIntoDocument(<Grandparent />);
expect(component.getDOMNode().childNodes[0].className)
.toBe('child xyz');
.toBe('xyz child');
});
it('should clone a composite component with new props', function() {
@@ -82,7 +82,7 @@ describe('cloneWithProps', function() {
});
var component = ReactTestUtils.renderIntoDocument(<Grandparent />);
expect(component.getDOMNode().childNodes[0].className)
.toBe('child xyz');
.toBe('xyz child');
});
it('should warn when cloning with refs', function() {
@@ -178,4 +178,17 @@ describe('cloneWithProps', function() {
ReactTestUtils.renderIntoDocument(<Grandparent />);
});
it('should overwrite props', function() {
var Component = React.createClass({
render: function() {
expect(this.props.myprop).toBe('xyz');
return <div />;
}
});
ReactTestUtils.renderIntoDocument(
cloneWithProps(<Component myprop="abc" />, {myprop: 'xyz'})
);
});
});
+6 -24
View File
@@ -21,13 +21,9 @@
var ReactPropTransferer = require('ReactPropTransferer');
var keyMirror = require('keyMirror');
var keyOf = require('keyOf');
var SpecialPropsToTransfer = keyMirror({
key: null,
children: null,
ref: null
});
var CHILDREN_PROP = keyOf({children: null});
/**
* Sometimes you want to change the props of a child passed to you. Usually
@@ -49,28 +45,14 @@ function cloneWithProps(child, props) {
}
}
var newProps = ReactPropTransferer.mergeProps(child.props, props);
var newProps = ReactPropTransferer.mergeProps(props, child.props);
// ReactPropTransferer does not transfer the `key` prop so do it manually. Do
// not transfer it from the original component.
if (props.hasOwnProperty(SpecialPropsToTransfer.key)) {
newProps.key = props.key;
}
// ReactPropTransferer does not transfer the `children` prop. Transfer it
// from `props` if it exists, otherwise use `child.props.children` if it is
// provided.
if (props.hasOwnProperty(SpecialPropsToTransfer.children)) {
newProps.children = props.children;
} else if (child.props.hasOwnProperty(SpecialPropsToTransfer.children)) {
// Use `child.props.children` if it is provided.
if (!newProps.hasOwnProperty(CHILDREN_PROP) &&
child.props.hasOwnProperty(CHILDREN_PROP)) {
newProps.children = child.props.children;
}
// ReactPropTransferer does not transfer `ref` so do it manually.
if (props.hasOwnProperty(SpecialPropsToTransfer.ref)) {
newProps.ref = props.ref;
}
return child.constructor.ConvenienceConstructor(newProps);
}