簡體   English   中英

通過道具將父組件的當前狀態傳遞給子組件

[英]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>
    );
  }
}

在這種情況下,我想將組件的整個狀態傳遞給孩子。 一種方法我能做到這一點,這感覺有點convul​​uted,是通過一個函數作為兒童中注入的狀態,並返回一個組成部分。 例如:

{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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM