【问题标题】:Left-align a scaled View/Text with react-native's Animated API使用 react-native 的动画 API 左对齐缩放的视图/文本
【发布时间】:2021-11-09 05:40:36
【问题描述】:

我试图构建一个“Material-UI-like”TextInput,带有一个在选择字段时会缩小的大标签。

我在缩放标签时遇到问题。应用transform: [{scale: ...}] 会缩小Text,但会在场中心附近这样做。我未能在缩放过程中保持标签左对齐,因为我需要动态地能够访问视图的宽度来偏移它,但我似乎无法使用正常方式获得它(即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>
  );
};

文本缩小一半后的示例:

请注意黄色视图 (Text) 由于缩放而不再左对齐。

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

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

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

【问题讨论】:

  • 我认为这是关于变换起源的。把transform-origin设置在左边就好了。但是rn不支持transform-origin。有一个类似的issue link

标签: react-native react-animated


【解决方案1】:

在我看来,您应该使用&lt;Animated.Text/&gt; 而不是&lt;Animated.View/&gt;。但它也会起作用。

如果您不使用alignSelf: 'flex-start',它将占用与Parent View 相同的空间。

这是我的解决方案:https://snack.expo.dev/@fanish/textinput-animation

      <Animated.Text
        style={{
          ...textStyle,
          transform: [{ scale }],
          alignSelf: 'flex-start',
        }}>
        Label
      </Animated.Text>

【讨论】:

  • 感谢您的提交!我仍然希望红色矩形的左边缘位于黄色矩形的左边缘之上,但事实并非如此。
  • 为此,您可以使用translateX 相对于onLayout={({ nativeEvent: { layout: { width } } }) =&gt; { setPositionX(-width / 2) }} https://snack.expo.dev/@fanish/textinput-animation
【解决方案2】:

我有两个解决方案:

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

2.如果你想计算它,你知道onLayout的初始大小并且你有scale让我们假设你使用的scale0.5onLayout 给了你100 然后你想要的margin-left(width-(width*scale))/2,在我们的例子中是25。但我认为没有必要这样做。

【讨论】:

  • 非常感谢您的关注。我编辑了我的问题(并添加了我自己的小吃)以更好地解释它。问题是在缩小后保持视图左对齐。 onLayout 在调整文本大小时似乎没有更新。
猜你喜欢
  • 1970-01-01
  • 2020-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-17
  • 1970-01-01
  • 2022-10-18
  • 1970-01-01
相关资源
最近更新 更多