首页 > 解决方案 > 如何将父状态传递给子组件

问题描述

基本上,我被困在将父母的组件状态传递给孩子。我有一个具有动态内容偏移侦听器的父组件,因此如果我向下或向上滚动,它会使用此偏移值更新状态。我还有一个子组件,在该子组件内我有另一个子组件(以便更轻松地浏览代码)。

那是父组件。我检查并在滚动发生时更新状态。

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}/>
   );
 }

Child的子组件

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>
   );
 }

我需要传递状态来为该孩子的子组件内的组件设置动画。

标签: reactjsreact-nativestatereact-native-ios

解决方案


将道具传递transformAnimation给转换{ scale: this.props.transformAnimation }

Child的子组件

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
}

推荐阅读