使用React在父componentDidMount上触发子动画

时间:2018-12-19 08:33:06

标签: javascript reactjs react-native animation

我在本机应用程序中使用react-native-circular-progress
安装父组件时,我想触发动画以填充它。

我该怎么做?我应该使用引用吗?

class Children extends Component {
  render() {
    return (
      <AnimatedCircularProgress
        ref={(ref) => { /* TODO: assign ref here maybe? */}}
        size={120}
        width={15} />
    )
  }
}

class Parent extends Component {

  componentDidMount() {
    // TODO: animate the component here
    // I should trigger the animation like this: this.circularProgress.animate(100, 8000, Easing.quad);
  }

  render() {
    return (
      <View>
        <Children />
        <Text>HEYA!</Text>
      </View>
    )
  }
}

1 个答案:

答案 0 :(得分:0)

我会尝试一些类似的方法。如果已安装组件,则将其作为道具发送的状态为true / false。然后检查您的子组件是什么道具。如果为true,则渲染动画。

class Children extends Component {
    componentDidMount() {
        if(this.props.isMounted) { //if the prop is true you should call the animation effect.
            //call the animation effect here.
        }
    }
    render() {
      return (
        <AnimatedCircularProgress
          ref={(ref) => { /* TODO: assign ref here maybe? */}}
          size={120}
          width={15} />
      )
    }
  }

  class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isMounted: false, //start with a state value of false
        }

      }

    componentDidMount() {
      // TODO: animate the component here
      // I should trigger the animation like this: this.circularProgress.animate(100, 8000, Easing.quad)
      if(!isMounted) {
          this.setState({isMounted: true}) // when it is mounted change state which will cause the child to rerender as it has this state as a prop
      }
    }

    render() {
      return (
        <View>
          <Children isMounted={this.state.isMounted} /> {/* send the state as a prop to the child*/}
          <Text>HEYA!</Text>
        </View>
      )
    }
  }