首页 > 解决方案 > React Native 动画基础

问题描述

所以我正在用 Expo 练习 React Native Reanimated 或 React Native 中的动画。我正在尝试使用动画从下到上打开一个屏幕。

当我按下Text它时,它将在我的父组件顶部显示另一个屏幕,动画从下到上。

但这是我得到的输出:

在此处输入图像描述

我想得到的输出:

在此处输入图像描述

这是我的代码:

class App extends React.Component {
state = {
 openHome: false
}

animation = new Value(0);

openHome = () => {
  this.setState({
    openHome: true
})
Animated.timing(this.animation, {
  duration: 300,
  toValue: 1
}).start();
}

render () {
const {animation} = this;
const translateY = animation.interpolate({
  inputRange: [0, 1],
  outputRange: [-height, 0],
  easing: Easing.inOut(Easing.ease)
});
return (
  <View style={styles.container}>
    <Text onPress={this.openHome}>Open up Home to start working on your app!</Text>
    {
      <Animated.View style={{ transform: [{ translateY }] }}>
        <Home open={this.state.openHome}/>
      </Animated.View>
    }
  </View>
);
}

}

我的子组件的代码是Home.js

const Home = props => {
if (!props.open) {
    return (
        <View style={styles.firstContainer}>
        </View>
    );
} else {
    return (
        <View style={styles.secondContainer}>
            <Text>Hello</Text>
        </View>
    );
}

}

const styles = StyleSheet.create({
firstContainer: {
    flex: 1, 
    justifyContent: 'center', 
    alignItems: 'center', 
    backgroundColor: 'transparent', 
    width: '100%'
},
secondContainer: {
    flex: 1, 
    justifyContent: 'center', 
    alignItems: 'center', 
    backgroundColor: 'red', 
    width: '100%',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0
}
})

标签: react-nativeanimationexporeact-native-reanimated

解决方案


如果要为值设置动画,则需要new Animated.Value(0)而不是new Value(0)首先。


推荐阅读