[英]Pass the current state of parent component to children through props
I have a very event-driven component. 我有一个非常事件驱动组件。 In this case, it is a video tag which will update its state with the current state of the playing video.
在这种情况下,它是一个视频标签将与播放视频的当前状态更新其状态。 For the sake of simplicity, imagine it looks something like this:
为了简单起见,假设它看起来是这样的:
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>
);
}
}
In this case, I want to pass the entire state of the component to the child. 在这种情况下,我想将组件的整个状态传递给孩子。 One way I can do it, which feels somewhat convuluted, is to pass a function as children which injects the state and returns a component.
一种方法我能做到这一点,这感觉有点convuluted,是通过一个函数作为儿童中注入的状态,并返回一个组成部分。 For example:
例如:
{children(this.state)}
Where the passed in component would be like: 凡在组件传递会像:
{(state) => <Progress {...state} />}
But I feel like there must be a way to pass the state of the parent component implicitly as props. 但是我觉得必须有隐含通过父组件的状态作为道具的方式。 How would this be done with React?
这将如何与作出反应呢?
Maybe you can try with: 也许您可以尝试:
<div>
{ React.Children.map(this.props.children,
child => React.cloneElement(child, {...this.state})
)}
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.