Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing state value from StyleSheet.create in ReactNative

I'm new in ReactNative and I have the following components:

  <View style={{flex: 1}}>
    <View style={styles.container}>
      <Animated.Image style= {styles.photo}
              source={{uri: this.props.user.picture.large}}/>
    </View>
    <View style={{backgroundColor:'whitesmoke', flex: 1}}></View>
  </View>

In the styles, I have the following:

const styles = StyleSheet.create({
  container: {
  flex: 0.5,
  backgroundColor: '#4dbce9',
  alignItems: 'center',
 },
 photo: {
  height: 150,
  width: 150,
  borderRadius: 75,
  borderWidth: 3,
  borderColor: 'white',
  transform: [                        // `transform` is an ordered array
            {scale: this.state.profileImgBounceVal}, 
          ]
  }
});

I got an error when I access this.state.profileImgBounceVal as its outside the component I know. Is there any workaround for this except including the styles inside the Animated.Image tag?

like image 835
Hossam Ghareeb Avatar asked Nov 22 '16 07:11

Hossam Ghareeb


Video Answer


1 Answers

You could use Stylesheet.flatten() to create a reusable style object in your component:

var animatedImageStyle = StyleSheet.flatten([
  styles.photo,
  {
    transform: [{scale:this.state.profileImgBounceVal}]
  }
])

<View style={{flex: 1}}>
  <View style={styles.container}>
    <Animated.Image style={animatedImageStyle}
            source={{uri: this.props.user.picture.large}}/>
  </View>
  <View style={{backgroundColor:'whitesmoke', flex: 1}}></View>
</View>
like image 161
Sven Avatar answered Nov 15 '22 05:11

Sven