React-Native Animated.interpolate不适用于样式组件

时间:2020-06-29 05:53:12

标签: reactjs react-native animation styled-components react-animated

有人知道为什么Animated.interpolate函数不能与Styled-Components一起使用。还是我做错了什么?

环境

  • 节点:12.13.0
  • npm:6.12.0
  • 本机:0.62
  • 样式化的组件:^ 5.1.1 => 5.1.1
  • @ types / styled-components:^ 5.1.0 => 5.1.0

复制步骤

  1. 使用 npx react-native init MyApp --template react-native-template-typescript

    创建一个新的TypeScript react-native项目
  2. 安装样式化组件 @ types /样式化组件

  3. 将App.tsx的代码替换为

import React, {useRef} from 'react';
import {
  View,
  Animated,
  Button,
} from 'react-native';
import styled, {ThemeProvider} from 'styled-components/native';


const App = () => {

// Animation
  const boxAnimation = useRef(new Animated.Value(0)).current;
  const moveIn = () => {
    Animated.timing(boxAnimation, {
      toValue: 1,
      duration: 2000,
      useNativeDriver: false,
    }).start();
  };
  const moveOut = () => {
    Animated.timing(boxAnimation, {
      toValue: 0,
      duration: 2000,
      useNativeDriver: false,
    }).start();
  };
  const fadeAnim = boxAnimation.interpolate({
    inputRange: [0, 1],
    outputRange: [0, 1],
  });
  const moveAnim = boxAnimation.interpolate({
    inputRange: [0, 1],
    outputRange: [0, -50],
  });

  return (
    <ThemeProvider theme={{}}>
      <AnimatedBox opacity={fadeAnim} pos={moveAnim}/>
      <Animated.View style={{
        position: 'absolute',
        top: 0,
        left: moveAnim,
        width: 50,
        height: 50,
        opacity: fadeAnim,
        backgroundColor: 'green',
      }}/>
      <View style={{marginTop: 100}}>
        <Button title={'MoveIn'} onPress={() => moveIn()}/>
        <Button title={'MoveOut'} onPress={() => moveOut()}/>
      </View>
    </ThemeProvider>
  );
};

const Box = styled.View`
  position: absolute;
  top: 0;
  left: ${props => props.pos}px;
  width: 50px;
  height: 50px;
  opacity: ${props => props.opacity};
  background-color: red;
`;
const AnimatedBox = Animated.createAnimatedComponent(Box);

export default App;

预期行为

如果您点击移入按钮红色框(彩色视图)应淡入并移入屏幕,如果您单击< strong>“移出按钮” 。 (请参见正常内嵌样式的绿色框预期行为)

实际行为

红色框将始终保持在-50位置,并通过单击 MoveOut按钮淡出,如果单击 MoveIn按钮 strong>(查看是否将红色框的pos设置为0)

->插值功能仅适用于 0,1 1、0 的输出范围,而实际上并非如此。使用正常的本机StyleSheet,插值函数将按预期工作。

GitHub问题: https://github.com/styled-components/styled-components/issues/3185

谢谢^^

1 个答案:

答案 0 :(得分:0)

我不熟悉“样式”,但是如果没有它,您可以尝试以恒定数字向左设置然后交换

pos={moveAnim}

使用

style={{ transform: [{ translateX: moveAnim }] }}