使用React.cloneElement()给子组件传值

react提供了一个克隆组件的API:

React.cloneElement(
	element,
	[props],
	[...child]
)

可以利用该方法,给子组件传值,使用如下:

class Parent extends Component{
	constructor(){
		super();
		this.state = {
			count: 1
		};
	}
	getChildren(){
		const _this = this;
		let { children } = _this.props;
		return React.Children.map(children, child => {
			return React.cloneElement(child, {
				count: _this.state.count
			});
		});
	}
	handleClick(){
		this.setState({
			count: this.state.count
		});
	}
	render(){
		return (
			
{ this.getChildren() }
) } } class Child extends Component{ render(){ return (
这是子组件:{ this.props.count }
) } } class Test extends Component{ render(){ return ( ) } }

点击父组件中的按钮,子组件中的数字会增加。父组件成功向子组件传值。

注意:

如果写成下面这样则无法传值:

class Test extends Component{
	render(){
		return (
			
				
这是子组件:{ this.props.count }
) } }

你可能感兴趣的:(react)