【发布时间】:2020-01-02 16:59:36
【问题描述】:
*编辑 - 对不起,我应该更清楚(我认为是新年快乐:/),我正在尝试将其从状态组件重构为带有 Hooks 的功能组件。除了我不确定将 ComponentWillMount 中的东西放在函数中的什么位置之外,我可以做所有事情,并假设我应该使用 Effect,但我无法让它工作!
我一直在玩 React Native,并使用了一些零碎的东西,并设法制作了一张可以在点击时翻转的小卡片。
我通常可以将组件重构为功能性组件,但我正在努力让这个组件正常工作 - 我不确定如何处理 ComponentsWillMount。我尝试将其放入 useEffect 中,但不行:/
import React, { Component } from 'react';
import { View, StyleSheet, Image, Animated, TouchableWithoutFeedback, Text } from 'react-native';
import TabBarIcon from '../components/TabBarIcon';
export default class App extends Component {
constructor(props) {
super(props)
this.state = {
animatedValue: new Animated.Value(0),
}
}
flipCard() {
if (this.value >= 90) {
Animated.spring(this.animatedValue,{
toValue: 0,
friction: 8,
tension: 10
}).start();
} else {
Animated.spring(this.animatedValue,{
toValue: 180,
friction: 8,
tension: 10
}).start();
}
}
componentWillMount() {
// Flipcard animation
this.animatedValue = new Animated.Value(0);
this.value = 0;
this.animatedValue.addListener(({ value }) => {
this.value = value;
})
this.frontInterpolate = this.animatedValue.interpolate({
inputRange: [0, 180],
outputRange: ['0deg', '180deg'],
})
this.backInterpolate = this.animatedValue.interpolate({
inputRange: [0, 180],
outputRange: ['180deg', '360deg']
})
this.frontOpacity = this.animatedValue.interpolate({
inputRange: [89, 90],
outputRange: [1, 0]
});
this.backOpacity = this.animatedValue.interpolate({
inputRange: [89, 90],
outputRange: [0, 1]
});
this.elevationFront = this.animatedValue.interpolate({
inputRange: [0, 25],
outputRange: [10, 0]
})
this.elevationBack = this.animatedValue.interpolate({
inputRange: [155, 180],
outputRange: [0, 10]
})
}
render() {
const frontAnimatedStyle = {
transform: [{ rotateY: this.frontInterpolate}]
}
const backAnimatedStyle = {
transform: [{ rotateY: this.backInterpolate }]
}
return (
<TouchableWithoutFeedback onPress={() => this.flipCard()} >
<View>
<Animated.View style={[frontAnimatedStyle, styles.paperFront,{elevation: this.elevationFront}, {opacity: this.frontOpacity}]}>
<Text style={{fontSize: 20,paddingTop: 8, paddingLeft: 8, color: 'black',lineHeight: 20}}>
Title Front - <Text style={{fontSize: 8}}>KPI</Text>
</Text>
<View style={{position: "absolute", paddingTop: 3, right: 8}}>
<TabBarIcon style={{color: "black"}} name={"md-more"} />
</View>
</Animated.View>
<Animated.View style={[backAnimatedStyle, styles.paperBack, {elevation: this.elevationBack}, {opacity: this.backOpacity}]}>
<Text>Back title</Text>
</Animated.View>
</View>
</TouchableWithoutFeedback>
);
}
}
const styles = StyleSheet.create({
paperFront : {
marginHorizontal: 15,
backgroundColor: "white",
minHeight: 200,
borderRadius: 5,
marginBottom: 15,
},
paperBack : {
top: -215,
marginHorizontal: 15,
backgroundColor: "white",
minHeight: 200,
borderRadius: 5,
marginBottom: 15,
}
});
【问题讨论】:
-
useEffect 专为钩子设计,但您在组件中使用
-
尝试将'componentWillMount'中的代码加载到'constructor'
标签: reactjs react-native