Home > Blockchain >  getting stuck in class to functional component conversion in react native
getting stuck in class to functional component conversion in react native

Time:01-05

I am new to react native here I tried to convert class components to functional components, I have tried to pass ref in the functional component in several ways also I have used hooks to handle the state but I am unable to do so please help me out thanks in advance.

export default class AddClick extends Component {
  constructor(props) {
    super(props);
    this.state = {
      changeAnim: false,
    };
  }
  componentDidMount() {
    setTimeout(() => {
      // handleScreenNavigation("OtpScreen", {});
      this.setState({ changeAnim: true }, () => {
        if (this.state.changeAnim) {
          this.animation.play(48, 48);
        }
      });
    }, 1500);

    this.animation.play();
  }
  render() {
    return (
      <View style={styles.container}>
        <View>
          <Animation
            ref={(animation) => {
              this.animation = animation;
              console.log("------@@@@@@@");
            }}
            style={styles.imageStyle}
            resizeMode="cover"
            loop={true}
            source={anim}
          />
        </View>
      </View>
    );
  }
}

here i have mentioned my attempt by functional component.

const AddClick = (props) => {
  const [changeAnimation, setChangeAnimation] = useState(false)
  useEffect(() => {
  setTimeout(()=>{
    setChangeAnimation(true),()=>{
      if(changeAnimation){
        animation.play(48,48)
      }
    }
  },1500)
  animation.play();
  }, [])
  return (
    <View style={styles.container}>
      <View>
        <Animation
          ref={(animation) => {
            this.animation = animation;
            console.log("------@@@@@@@");
          }}
          style={styles.imageStyle}
          resizeMode="cover"
          loop={true}
          source={anim}
        />
      </View>
    </View>
  );
}

AppRegistry.registerComponent("AddClick", () => AddClick);

CodePudding user response:

You cannot use this in a functional component. You can find the updated code here:

const AddClick = (props) => {
  const [changeAnimation, setChangeAnimation] = useState(false)
  let animation; // Create a local variable

 useEffect(() => {
  setTimeout(()=>{
    setChangeAnimation(true),()=>{
      if(changeAnimation){
        animation.play(48,48)
      }
    }
  },1500)
   animation.play(); // Make sure to check if animation is defined before calling any methods
  }, [])
  return (
    <View style={styles.container}>
      <View>
        <Animation
          ref={(anim) => {
            animation = anim;
            console.log("------@@@@@@@");
          }}
          style={styles.imageStyle}
          resizeMode="cover"
          loop={true}
          source={anim}
        />
      </View>
    </View>
  );
}

AppRegistry.registerComponent("AddClick", () => AddClick);
  •  Tags:  
  • Related