const ComponentButton = props => { const { addonAfter, children } = props; const button = <button key='button'>{ children }</button> const list = [button, addonAfter ? React.cloneElement(addonAfter, { key: 'button-addon' } : null) return <div>{ list } <div> }
总结在开发复杂组件中,经常会根据需要给子组件添加不同的功能或者显示效果,react 元素本身是不可变的 (immutable) 对象, props.children 事实上并不是 children 本身,它只是 children 的描述符 (descriptor) ,我们不能修改任何它的任何属性,只能读到其中的内容,因此 React.cloneElement 允许我们拷贝它的元素,并且修改或者添加新的 props 从而达到我们的目的。
当然,得益于 react 强大的组合模式,这并不仅仅局限于 props.children ,不管是 props.left 还是 props.right 或者任何其它的 props 传进来的内容,只要是合法的 react 元素,我们都可以使用这个 React.cloneElement 对其进行操作。