React提供了克隆组件API:
React.cloneElement(
element,
[props],
[...child]
)
可以利用该方法,给子组件传值
父组件:
import React from 'react'
class Parent extends React.Component<any, any>{
state = {
count: 1
};
getChildren() {
const _this = this;
let { children } = _this.props;
return React.Children.map(children, child => {
const customNode = child as React.ReactElement<any>;
if (!customNode || typeof customNode !== 'object') {
return undefined;
}
return React.cloneElement(customNode, {
count: _this.state.count
});
});
}
handleClick() {
this.setState({
count: this.state.count+1
});
}
render() {
return (
<div>
<button onClick={this.handleClick.bind(this)}>点击增加次数</button>
{this.getChildren()}
</div>
)
}
}
export default Parent;
export class Child extends React.Component<any>{
render() {
return (
<div>
这是子组件:{this.props.count}
</div>
)
}
}
使用:
import Parent, { Child } from './components/Parent';
*
*
*
return (
<Parent>
<Child />
</Parent>
)
*
*