首页 > 解决方案 > 在本机反应中为图像设置动画

问题描述

我对原生反应完全陌生,我正在尝试为图像制作动画,任何建议都会有所帮助!

import React, { Component } from 'react';
import { Animated, Easing } from 'react-native';
import FontAwesome5Pro from 'react-native-vector-icons/FontAwesome5Pro';

class AnimateIcon extends Component {
  spinValue = new Animated.Value(0);

  componentDidMount() {
    this.spin();
  }

  spin = () => {
    this.spinValue.setValue(0);

    Animated.timing(this.spinValue, {
      toValue: 1,
      duration: 1000,
      easing: Easing.linear,
      useNativeDriver: true,
    }).start(() => this.spin());
  };

  render() {
    const { style, children } = this.props;
    const rotate = this.spinValue.interpolate({
      inputRange: [0, 1],
      outputRange: ['0deg', '360deg'],
    });

    return (
      <Animated.View style={{ transform: [{ rotate }] }}>
        <FontAwesome5Pro style={style}>{children}</FontAwesome5Pro>
      </Animated.View>
    );
  }
}

export default AnimateIcon;

我收到以下错误:

“类型 'Readonly<{}> 和 Readonly<{ children?: ReactNode; }> 上不存在属性 'style'

标签: androidiosreact-native

解决方案


因为您使用的是 TypeScript,所以您需要定义您propsprops.style. 此外,您需要记住保留您Animated.Value的 a state,因为 React 使用更改state来确定何时重新渲染。

import React, { Component } from 'react'
import { Animated, Easing, ViewStyle } from 'react-native'
import FontAwesome5Pro from 'react-native-vector-icons/FontAwesome5Pro'

interface AnimateIconProps {
    style?: ViewStyle
}

class AnimateIcon extends Component<AnimateIconProps, { spinValue?: Animated.Value }> {
    constructor (props: AnimateIconProps) {
        super(props)
        this.state = {
            spinValue: new Animated.Value(0),
        }
    }

    componentDidMount () {
        this.spin()
    }

    spin = () => {
        this.state.spinValue.setValue(0)
        Animated.timing(this.state.spinValue, {
            toValue: 1,
            duration: 1000,
            easing: Easing.linear,
            useNativeDriver: true,
        }).start(() => this.spin())
    }

    render () {
        const { style, children } = this.props
        const rotate = this.state.spinValue.interpolate({
            inputRange: [0, 1],
            outputRange: ['0deg', '360deg'],
        })

        return (
            <Animated.View style={{ transform: [{ rotate }] }}>
                <FontAwesome5Pro style={style}>{children}</FontAwesome5Pro>
            </Animated.View>
        )
    }
}

export default AnimateIcon

推荐阅读