|
1 | 1 | --- |
2 | 2 | id: clone-with-props |
3 | | -title: Cloning ReactElement |
| 3 | +title: Cloning ReactElements |
4 | 4 | permalink: clone-with-props.html |
5 | 5 | prev: test-utils.html |
6 | 6 | next: create-fragment.html |
7 | 7 | --- |
8 | 8 |
|
9 | | -In rare situations an element may want to change the props of an element that it doesn't own (like changing the `className` of an element passed as `this.props.children`). Other times it may want to make multiple copies of an element passed to it. `cloneWithProps()` makes this possible. |
| 9 | +> Note: |
| 10 | +> `cloneWithProps` is deprecated. Use [React.cloneElement](top-level-api.html#react.cloneelement) instead. |
10 | 11 |
|
11 | | -#### `ReactElement React.addons.cloneWithProps(ReactElement element, object? extraProps)` |
| 12 | +In rare situations, you may want to create a copy of a React element with different props from those of the original element. One example is cloning the elements passed into `this.props.children` and rendering them with different props: |
12 | 13 |
|
13 | | -Do a shallow copy of `element` and merge any props provided by `extraProps`. The `className` and `style` props will be merged intelligently. |
| 14 | +```js |
| 15 | +var _makeBlue = function(element) { |
| 16 | + return React.addons.cloneWithProps(element, {style: {color: 'blue'}}); |
| 17 | +}; |
14 | 18 |
|
15 | | -> Note: |
16 | | -> |
17 | | -> `cloneWithProps` does not transfer `key` to the cloned element. If you wish to preserve the key, add it to the `extraProps` object: |
18 | | -> |
19 | | -> ```js |
20 | | -> var clonedElement = cloneWithProps(originalElement, { key : originalElement.key }); |
21 | | -> ``` |
22 | | -> |
23 | | -> `ref` is similarly not preserved. |
| 19 | +var Blue = React.createClass({ |
| 20 | + render: function() { |
| 21 | + var blueChildren = React.Children.map(this.props.children, _makeBlue); |
| 22 | + return <div>{blueChildren}</div>; |
| 23 | + } |
| 24 | +}); |
| 25 | + |
| 26 | +React.render( |
| 27 | + <Blue> |
| 28 | + <p>This text is blue.</p> |
| 29 | + </Blue>, |
| 30 | + document.getElementById('container') |
| 31 | +); |
| 32 | +``` |
| 33 | + |
| 34 | +`cloneWithProps` does not transfer `key` or `ref` to the cloned element. `className` and `style` props are automatically merged. |
0 commit comments