简体   繁体   English

如何在 React Native 的 function 中加载 Lottie Animation?

[英]How to load Lottie Animation inside a function in React Native?

My idea is something similar to the "instagram like", when you click it, it should render a heart animation我的想法类似于“instagram like”,当你点击它时,它应该呈现一颗心 animation

My code: when you click in the heart button, it calls the "changeFavorite" function, which will set 'favorite = true' in the API and also renders the animation.我的代码:当您单击心形按钮时,它会调用“changeFavorite”function,这将在 API 中设置“favorite = true”,并呈现 Z6F1C25ED1523962F1BBF9DEE9BE。 It updates the API, but doesn't return the JSX with Lottie Animation它更新了 API,但不返回带有 Lottie Animation 的 JSX

//Like Button //点赞按钮

<TouchableOpacity onPress={changeFavorite} style={{borderRadius: 50, marginRight: 16, marginTop: 16}}>
       <MaterialIcons name="favorite" size={30}  color={favorito == 1 ? 'red' : '#fff'}/></TouchableOpacity>

//changeFavorite //更改收藏夹

async function changeFavorite() {
        try {
            await api.put(`favoritos/${local.id}`, {
                local_id: local.id
            }).then(res => {
                setFavorito(res.data)
                if(favorito === 0) {
                    console.log("like")
                    return (
                        <View style={{flex: 1, height: 300, width: 300, position:"absolute"}}>
                            <LottieView
                            source={require('../../assets/heart.json')}    
                            resizeMode="cover"
                            autoPlay
                            />
                        </View>
                    )
               }
                else {
                    console.log("deslike")
                }
            })
        } catch (error) {
            console.log(error)
        }        
}

Set reference to your Lottie.设置对您的 Lottie 的引用。

export default class App extends Component {

  changeFavorite = () => {
    this.Lottie.play();       //play it inside your function call
  };

  render() {
    return (
      <LottieView
        autoPlay={false}
        loop={false}
        ref={(e) => {
          this.Lottie = e;     //set a reference variable
        }}
        ...
      />
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM