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