javascript - 如果特定 prop 发生变化,则重新渲染整个组件

标签 javascript reactjs react-native

我有这个组件:

<Animatable.Text animation='pulse' style={styles.toggle}>Items: {props.items}</Animatable.Text>

每当我获得 props.items 的更新时,组件都会重新渲染更改、值,但动画不会重新出现。

如何让动画重新出现?导致 Prop 再次运行?基本上完全重新渲染组件导致它重新加载动画 Prop ?

Note that the animation only runs on load, not state change

完整组件:

import React, { Component } from 'react'
import { View , TextInput, Button, Alert, StyleSheet } from 'react-
native'
import * as Animatable from 'react-native-animatable'

export default class Adder extends Component {
constructor(props) {
    super(props)
    this.state = {
        text: '',
        items: this.props.items
    }
}

render() {
    const { add, clear, items } = this.props
 return (
     <View style={{paddingTop: 50}}>
      <TextInput placeholder='Buy...' autoCorrect={false} value={this.state.text} onChangeText={(text) => this.setState({text})} style={{ backgroundColor: '#ededed', height: 60, textAlign: 'center', marginBottom: 10 }} />
      <View style={{flexDirection: 'row', justifyContent: 'space-around'}}>    
          <Button
          title='Add Item' 
          onPress={() => {
          this.state.text != '' ? add(this.state.text) : Alert.alert('Enter Groceries')
          this.setState({text: ''})
          }}
          />  
        <Animatable.Text animation='pulse' style={styles.toggle}>Items: {this.state.items}</Animatable.Text>
        <Button title='Mark All' onPress={() => clear()} />
      </View>
    </View>
 )
}
}
const styles = StyleSheet.create({
toggle: {
    width: 100,
    backgroundColor: '#333',
    borderRadius: 3,
    padding: 5,
    fontSize: 14,
    alignSelf: 'center',
    textAlign: 'center',
    color: 'rgba(255, 255, 255, 1)',
  }
})

最佳答案

由于 Animatable 不会在状态更改时重新出现动画,因此您可能希望强制调用动画。实现此目的的一种方法是在可动画文本上使用引用并在 componentWillUpdate 上调用它。所以像下面这样:

// this gets triggered when you get a new state
componentWillUpdate() {
  // pulsate for 800 ms
  this.animatedText.pulse(800);
}


//.. render method
<Animatable.Text 
    animation='pulse' style={styles.toggle} 
    ref={(text) => { this.animatedText = text; }}>
        Items: {this.state.items}
</Animatable.Text>

关于javascript - 如果特定 prop 发生变化,则重新渲染整个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44772953/

相关文章:

javascript - 如何纠正流量警告: destructuring (Missing annotation)

android - Navigator 与 NavigatorIOS React Native 应用程序

javascript - 替换javascript中的正则表达式子字符串

Javascript从数据中获取 key (不显示 key )

javascript - 为什么 React Router 更改 URL 但不更改 View

javascript - react 。 onClick 事件未触发

javascript - React Native 从外部源加载 JSX 并在运行时对其进行转换

css - 有没有更好的方法可以在柔性显示中的元素之间保持相同的间隙空间?

javascript - 在不丢失宽高比的情况下调整图像大小

javascript - Angular4 View 不更新 setTimeout 中的数据集