场景
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class A extends Component {
render() {
const {children} = this.props,
newChildren = React.Children.map(children, child =>
React.cloneElement(
child,
{ onChange: e => alert(e.target.value) }
));
return (
<div>
{newChildren}
</div>
);
}
}
class Page extends Component {
render() {
return (
<A>
<input />
<input />
</A>
);
}
}
ReactDOM.render(
<Page />,
document.getElementById('app')
);
解释
(1)this.props.children
是组件props
的隐藏属性,它的值是一个数组,
数组元素为ReactElement。
(2)React.cloneElement
用来克隆ReactElement,返回一个新的元素。
以下用法是等价的:
React.cloneElement(
element,
props,
children
);
<element.type {...element.props} {...props}>{children}</element.type>
(3)React.Children
提供了一些工具函数来处理this.props.children
。
包括:React.Children.map
React.Children.forEach
React.Children.count
React.Children.only
React.Children.toArray
参考
React Top-Level API: cloneElement()
React Top-Level API: React.Children