Javascript 在react native中使用简单的滚动动画
我花了很长时间试图让一个简单的滚动动画在react native中工作 我试图实现的是,组件在被点击后从屏幕的右边缘滚动 无论我对这个类做什么,当我点击元素时,我都会得到试图分配给readonly属性的错误Javascript 在react native中使用简单的滚动动画,javascript,reactjs,react-native,react-animated,Javascript,Reactjs,React Native,React Animated,我花了很长时间试图让一个简单的滚动动画在react native中工作 我试图实现的是,组件在被点击后从屏幕的右边缘滚动 无论我对这个类做什么,当我点击元素时,我都会得到试图分配给readonly属性的错误,我不知道为什么 我在animateOut函数中看到的唯一赋值是this.anim.offsetX,但这不能是只读属性,因为我在构造函数中明确地对其赋值很好 我尝试过但没有帮助的事情: 将可设置动画的值从state属性中去掉,这样animated.timing调用就不会试图直接改变state属
,我不知道为什么
我在animateOut
函数中看到的唯一赋值是this.anim.offsetX
,但这不能是只读属性,因为我在构造函数中明确地对其赋值很好
我尝试过但没有帮助的事情:
将可设置动画的值从state属性中去掉,这样animated.timing调用就不会试图直接改变state属性
简化动画调用,以便只有一个动画会改变此值
仔细阅读:上的示例,看看我在做什么
查找有关堆栈溢出的现有问题。我发现,但那里的错误条件似乎不适用于我的代码
有人能告诉我我做错了什么吗
export default class SquareBlock extends Component {
constructor(props) {
super(props);
this.anim = {};
this.anim.offsetX = new Animated.Value(0);
}
animateOut() {
console.log("animating out");
console.log("X offset:",this.anim.offsetX)
Animated.timing(
this.anim.offsetX,
{ toValue: 120,
duration: 500
}
).start();
}
render() {
let content = this.props.content || "Tappable";
let offsetX;
offsetX = this.anim.offsetX;
return (
<Animated.View >
<TouchableNativeFeedback onPress={ () => this.animateOut() }>
<View style={ [styles.outerBox, { "left": offsetX } ] } >
<Text style={ styles.text }> { content }</Text>
</View>
</TouchableNativeFeedback>
</Animated.View>
)
}
}
导出默认类SquareBlock扩展组件{
建造师(道具){
超级(道具);
this.anim={};
this.anim.offsetX=新的动画.Value(0);
}
动画输出(){
console.log(“动画输出”);
log(“X偏移量:”,this.anim.offsetX)
时间(
这个.anim.offsetX,
{toValue:120,
持续时间:500
}
).start();
}
render(){
让content=this.props.content | |“可点击”;
让我们抵消;
offsetX=this.anim.offsetX;
返回(
this.animateOut()}>
{content}
)
}
}
您必须设置X和Y的值,并将其设置为Animated.View
此外,还必须为动画提供样式(至少样式是动画使用的道具的名称)
试试这个:
在componentWillMount()中有一个您想要开始的位置
在动画.View中,您必须提供此.position作为style//如上所述,style是动画拍摄的道具的名称
<Animated.View style={this.position.getLayout()}> //very important
<TouchableNativeFeedback onPress={ () => this.animateOut() }>
<View style={ [styles.outerBox, { "left": offsetX } ] } >
<Text style={ styles.text }> { content }</Text>
</View>
</TouchableNativeFeedback>
</Animated.View>
这应该能正常工作
<Animated.View style={this.position.getLayout()}> //very important
<TouchableNativeFeedback onPress={ () => this.animateOut() }>
<View style={ [styles.outerBox, { "left": offsetX } ] } >
<Text style={ styles.text }> { content }</Text>
</View>
</TouchableNativeFeedback>
</Animated.View>
animateOut() {
this.position ,
Animated.timing(this.position, {
toValue: { x: this.position + 20 , y: 0},
duration: 250
}).start();
}