react-native - 使用react-native的动画API左对齐缩放的 View /文本

标签 react-native react-animated

我试图构建一个“类似于 Material-UI”的 TextInput,其带有一个大标签,当选择字段时,该标签会缩小。

我在缩放标签时遇到问题。应用变换:[{scale: ...}] 会缩小文本,但会围绕字段中心进行。我无法在缩放过程中保持标签左对齐,因为我需要动态地能够访问 View 的宽度来偏移它,但我似乎无法使用正常方式获取它(即onLayout,动画过程中似乎没有触发)。

以下是演示该问题的示例:

import React from 'react';
import { View, Text, TextInput, Animated } from 'react-native';

export const F = (): JSX.Element => {
  const scale = React.useRef(new Animated.Value(0.0)).current;

  React.useEffect(() => {
    const animation = Animated.timing(scale, {
      toValue: 1.0,
      duration: 1000,
      useNativeDriver: true,
    });

    animation.start();
  }, []);

  return (
    <View style={{ backgroundColor: 'red' }}>
      <Animated.View
        style={{
          transform: [
            {
              scale: scale.interpolate({
                inputRange: [0, 1],
                outputRange: [1, 0.5],
              }),
            },
          ],
          backgroundColor: 'yellow',
        }}
        onLayout={(e) => console.log({ view: e.nativeEvent.layout })}>
        <Text onLayout={(e) => console.log({ text: e.nativeEvent.layout })}>
          Label
        </Text>
      </Animated.View>
      <TextInput style={{ backgroundColor: 'blue' }} />
    </View>
  );
};

文本缩放一半后的示例:

Issue

请注意黄色 View (文本)如何因缩放而不再左对齐。

我创建了一个堆栈来解释我想要完成的任务:

https://snack.expo.dev/@bertrand-caron/trembling-beef-jerky

我希望Label View (黄色)在缩放时保持左对齐,而不是在红色 View 内居中缩小。

最佳答案

我有两个解决方案:

1. 为此,我创建了一个小吃:https://snack.expo.dev/PFN07UigC 。 让我知道是否合适。对于左对齐,我刚刚使用 justify-content:'flex-start'到它的容器。

2. 如果您想计算它,您可以通过 onLayout 知道初始大小。你有 scale让我们假设scale您正在使用的是 0.5onLayout给了你100然后margin-left您需要的是 (width-(width*scale))/2在我们的例子中25 。但我认为没有任何必要。

关于react-native - 使用react-native的动画API左对齐缩放的 View /文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69170986/

相关文章:

android - react native : catch volume buttons press (not for volume adjusting)

javascript - Undefined 不是对象 animated.interpolate react native

reactjs - 将组件放置在 React Native 中父组件的特定坐标上

animation - 父边界内的可拖动 View

java - 未知源文件 : com. android.dex.DexException:多个 dex 文件定义 Lcom/google/android/gms/internal/zzpq;

javascript - 如何使用 Material 下拉菜单获取选定的值?

react-native - 在 React Native 中实现 Safari View Controller

android - React Native Android 调试 keystore

javascript - Animated.Value 的 Prop 类型?

reactjs - 为什么只有一个 react native 并行动画在运行而另一个没有运行?