【问题标题】:How to load Lottie Animation inside a function in React Native?如何在 React Native 的函数中加载 Lottie 动画?
【发布时间】:2020-08-23 09:28:05
【问题描述】:

我的想法类似于“instagram like”,当你点击它时,它应该渲染一个心脏动画

我的代码:当你点击心形按钮时,它会调用“changeFavorite”函数,该函数会在API中设置'favorite = true'并渲染动画。它更新了 API,但不返回带有 Lottie Animation 的 JSX

//点赞按钮

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

//更改收藏

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

【问题讨论】:

  • 抱歉问题中的错误,React Native 不适用于 JSX
  • 请给我看你的完整组件,因为我无法看到这个返回的组件将在哪里使用。

标签: javascript react-native animation jsx lottie


【解决方案1】:

设置对您的 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
        }}
        ...
      />
    );
  }
}

【讨论】:

  • 这是一堂课。这个问题专门询问了一个函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-05
  • 1970-01-01
  • 2020-01-01
  • 2018-06-12
  • 2020-02-08
  • 1970-01-01
  • 2020-07-04
相关资源
最近更新 更多