使用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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM