Browse Source
Updated documentation to reflect that using React.cloneElement is the new way to copy an element and preserve `key` and `ref`. Fixes #3432, closes #3447.main
committed by
Ben Alpert
2 changed files with 25 additions and 14 deletions
@ -1,23 +1,34 @@ |
|||
--- |
|||
id: clone-with-props |
|||
title: Cloning ReactElement |
|||
title: Cloning ReactElements |
|||
permalink: clone-with-props.html |
|||
prev: test-utils.html |
|||
next: create-fragment.html |
|||
--- |
|||
|
|||
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. |
|||
> Note: |
|||
> `cloneWithProps` is deprecated. Use [React.cloneElement](top-level-api.html#react.cloneelement) instead. |
|||
|
|||
#### `ReactElement React.addons.cloneWithProps(ReactElement element, object? extraProps)` |
|||
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: |
|||
|
|||
Do a shallow copy of `element` and merge any props provided by `extraProps`. The `className` and `style` props will be merged intelligently. |
|||
```js |
|||
var _makeBlue = function(element) { |
|||
return React.addons.cloneWithProps(element, {style: {color: 'blue'}}); |
|||
}; |
|||
|
|||
> Note: |
|||
> |
|||
> `cloneWithProps` does not transfer `key` to the cloned element. If you wish to preserve the key, add it to the `extraProps` object: |
|||
> |
|||
> ```js |
|||
> var clonedElement = cloneWithProps(originalElement, { key : originalElement.key }); |
|||
> ``` |
|||
> |
|||
> `ref` is similarly not preserved. |
|||
var Blue = React.createClass({ |
|||
render: function() { |
|||
var blueChildren = React.Children.map(this.props.children, _makeBlue); |
|||
return <div>{blueChildren}</div>; |
|||
} |
|||
}); |
|||
|
|||
React.render( |
|||
<Blue> |
|||
<p>This text is blue.</p> |
|||
</Blue>, |
|||
document.getElementById('container') |
|||
); |
|||
``` |
|||
|
|||
`cloneWithProps` does not transfer `key` or `ref` to the cloned element. `className` and `style` props are automatically merged. |
|||
|
Loading…
Reference in new issue