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