使用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 (
			<div>
				<button onClick={ this.handleClick.bind(this) }>点击增加次数</button>
				{ this.getChildren() }
			</div>
		)
	}
}
class Child extends Component{
	render(){
		return (
			<div>
				这是子组件:{ this.props.count }
			</div>
		)
	}
}
class Test extends Component{
	render(){
		return (
			<Parent>
				<Child />
			</Parent>
		)
	}
}

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

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

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

本文转载自:https://blog.csdn.net/csm0912/article/details/85244970

原文地址:https://www.cnblogs.com/smart-girl/p/react.html