簡體   English   中英

如何將父狀態傳遞給子組件

[英]How to pass parent's state to children components

基本上,我堅持將父母的組件狀態傳遞給孩子。 我有一個具有動態內容偏移偵聽器的父組件,所以如果我向下或向上滾動它會更新具有此偏移值的狀態。 我還有一個子組件,在那個子組件中我有另一個子組件(為了更容易通過代碼導航)。

這是父組件。 我檢查了,每當滾動發生時狀態都在更新。

constructor(props) {
super(props);
this.state = {
  contentOffset: 1
}
this.onScrollEvent = this.onScrollEvent.bind(this);
}


onScrollEvent = event => {
this.setState(
  {
    contentOffset: event.nativeEvent.contentOffset.y,
  }
)
}               
render() { 
   return (                                        
   <ScrollView 
    showsVerticalScrollIndicator={false}
    onScroll={this.onScrollEvent.bind(this)>
       <ChildOne
          animation={this.state.contentOffset}/>
   );
 }

兒童組件

constructor(props) {
    super(props);
}
render() { 
   return (   
   <NestedChild 
            handleClick={this.openSettingsInHeader} 
            header="What the..."
            transformAnimation={this.props.animation}/>
   );
 }

孩子的孩子組成部分

constructor(props) {
    super(props);
    this.state = {
        AnimatedTextValue: new Animated.Value(0),
        ProfileOffset: this.props.transformAnimation
    }
}

render() { 

   const animatedStyles = {
        transform: [
          { scale: 0 }]} //how to link the AnimatedTextValue to ProfileOffset? 
   return (   
   <Animated.Text style={[styles.nameStyle,animatedStyles]}>Hi!</Animated.Text>
   );
 }

我需要傳遞狀態來為子組件子組件中的組件設置動畫。

傳遞道具transformAnimation{ scale: this.props.transformAnimation }

孩子的孩子組成部分

render() { 
   const animatedStyles = {
        transform: [
          { scale: this.props.transformAnimation }]} // <<====  
   return (   
   <Animated.Text style={[styles.nameStyle,animatedStyles]}>Hi!</Animated.Text>
   );
 }

並從狀態ProfileOffset中刪除您不需要處於狀態。 從父母那里獲得價值的道具 - 每當做出改變時。

 this.state = {
    AnimatedTextValue: new Animated.Value(0),
    ProfileOffset: this.props.transformAnimation   // <==== remove this
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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