【问题标题】:How to pass parent's state to children components如何将父状态传递给子组件
【发布时间】:2019-08-15 18:24:51
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你有没有试过把它作为道具传给孩子,然后再从孩子传给孙子作为道具?

标签: reactjs react-native state react-native-ios


【解决方案1】:

将 props 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
}

【讨论】:

  • 谢谢!它可以工作,但是对于更复杂的东西,比如函数 .interpolate(在 Animated 库中),我们需要以某种方式将它与 AnimatedTextValue 链接起来:new Animated.Value(0)。可能你能帮我吗?感谢您的回答。
  • 欢迎您,您能否使用有关该问题的代码和更多信息更新帖子。目前在上班,没时间。但我可以稍后检查并尝试提供帮助。
  • Nikola,谢谢,我认为最好从我的问题开始另一个问题。你真的解决了这个问题!
猜你喜欢
  • 1970-01-01
  • 2017-05-31
  • 2014-12-18
  • 2020-07-04
  • 2019-02-17
  • 2019-04-02
  • 2020-06-21
  • 2022-07-15
  • 1970-01-01
相关资源
最近更新 更多