[英]Pass the current state of parent component to children through props
我有一个非常事件驱动组件。 在这种情况下,它是一个视频标签将与播放视频的当前状态更新其状态。 为了简单起见,假设它看起来是这样的:
export default class VideoPlayer extends Component {
state = {
canPlay: false,
duration: 0,
position: 0,
};
onCanPlay = () => this.setState({ canPlay: true });
onTimeUpdate = ({ target: { position, duration } }) => this.setState({ position, duration });
render() {
const { src, children } = this.props;
return (
<div className={styles.container}>
<video
src={src}
onCanPlay={this.onCanPlay}
onTimeUpdate={this.onTimeUpdate}
/>
{children}
</div>
);
}
}
在这种情况下,我想将组件的整个状态传递给孩子。 一种方法我能做到这一点,这感觉有点convuluted,是通过一个函数作为儿童中注入的状态,并返回一个组成部分。 例如:
{children(this.state)}
凡在组件传递会像:
{(state) => <Progress {...state} />}
但是我觉得必须有隐含通过父组件的状态作为道具的方式。 这将如何与作出反应呢?
也许您可以尝试:
<div>
{ React.Children.map(this.props.children,
child => React.cloneElement(child, {...this.state})
)}
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.