简体   繁体   中英

react native “attempt to set value to an immutable object”

I'm creating a draggable box. which I can drag anywhere on the screen but I'm getting this error which says that " You attempted to set the key _value on an object that is meant to be immutable and has been frozen ". Can anyone tell me what am I doing wrong.

My Code:

import React, { Component } from 'react'
import {
  AppRegistry,
  StyleSheet,
  Text,
  Button,
  ScrollView,
  Dimensions,
  PanResponder,
  Animated,
  View
} from 'react-native'

import { StackNavigator } from 'react-navigation'




export default class Home extends Component{

componentWillMount(){

  this.animatedValue = new Animated.ValueXY();

this.panResponder = PanResponder.create({

 onStartShouldSetPanResponder: (evt, gestureState) => true,
  onMoveShouldSetPanResponder: (evt, gestureState) => true,
  onPanResponderGrant: (e, gestureState) => {



      },

  onPanResponderMove:Animated.event([


null,{dx: this.animatedValue.x , dy:this.animatedValue.y}

    ]),  
  onPanResponderRelease: (e, gestureState) => { 
      },       
})
}

  render(){

    const animatedStyle = {

      transform:this.animatedValue.getTranslateTransform()
    }

    return(

        <View style={styles.container}>

        <Animated.View style={[styles.box ,animatedStyle]} {...this.panResponder.panHandlers}>


        <Text>Home</Text>


        </Animated.View>
        </View>
      )
  }
}


var styles = StyleSheet.create({
  container: {
    flex: 1,
    marginLeft: 10,
    marginRight: 10,
    alignItems: 'stretch',
    justifyContent: 'center',
  },

  box:{

height:90,
width:90,
textAlign:'center'



  }
});

就我而言,我收到此错误是因为我忘记将View更改为Animated.View

Try this out. This will solve your issue. You need to initialize animatedValue in state object to make it work.

constructor(props) {
  super(props);
  this.state = {
    animatedValue: new Animated.ValueXY()
  }
}

onPanResponderMove:Animated.event([
 null,{dx: this.state.animatedValue.x , dy:this.state.animatedValue.y}
]),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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