如果特定道具发生变化,则重新渲染整个组件

时间:2017-06-27 05:43:09

标签: javascript reactjs react-native

我有这个组件:

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

每当我获得props.items的更新时,Component会重新呈现更改,即值,但动画不会重新出现。

如何重新显示动画?导致道具再次运行?基本上完全重新渲染组件导致它重新加载动画道具?

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

1 个答案:

答案 0 :(得分:0)

由于Animatable不会在状态发生变化时重新出现动画,因此您可能需要强制调用动画。一种方法是在Animatable文本上使用ref并在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>
相关问题