【问题标题】:How to add animation to a view changing its height in react native?如何将动画添加到视图中以更改其高度以响应本机?
【发布时间】:2025-12-29 20:55:06
【问题描述】:

我正在尝试根据几个条件增加和减少一个矩形的高度......任务完成了,但是我想让高度平滑而逐渐变化。

当我的 CSS 动态变化时,我如何在 react native 中做到这一点?

 getBarStyle() {
    if (this.state.value < this.state.minValue) {
      return {
        height: 0
      };
    }
    let accurateHeight;
    accurateHeight = (this.state.value * (this.state.graphHeight - lineDiffValue);

    return {
      height: accurateHeight,
      transition: "height 2s"
    };
  }

  render() {
    return (
            <View style={[styles.rectangle, this.getBarStyle()]} />
        )
}

【问题讨论】:

    标签: css react-native


    【解决方案1】:

    首先,用 View 的起始值创建一个Animated.Value

    constructor() {
      this.animatedValue = new Animated.Value(50);
    }
    

    然后,创建一个动画高度的函数。下面的示例将从50 动画到100

    startAnimation = () => {
      Animated.timing(this.animatedValue, {
        toValue: 100
      }).start();
    }
    

    最后,将您的动画样式传递给您的视图。您需要使用Animated.View,而不是View

    render() {
      return (
        <Animated.View style={{ height: this.animatedValue }} />
      )
    }
    

    别忘了import { Animated } from 'react-native';

    【讨论】:

    • 不要忘记调用函数 startAnimation 因为它不会调用自己
    • 我不认为这是公认的答案。我收到错误消息:本机动画模块不支持样式属性“高度”。
    • @CraigHowell Same
    • useNativeDriver: false
    【解决方案2】:

    错误

    <Animated.View style={{ height: this.animatedValue }} />
    

    错误:原生动画模块不支持样式属性“高度”。

    正如 React-Native 文档所说,您只能为非布局属性设置动画。支持 Transform 属性,因此您可以使用 transform.scaleY 而不是更改高度 :((

    所以..

    试试我的解决方案

    constructor(props: any)
    {
        this.state.isDisplay = true;
        this.state.animatedView = new Animated.Value(100);
        this.state.animatedViewInterpolate = 
        this.state.animatedView.interpolate({ inputRange: [0, 100], outputRange: ["0%", "100%"] });
        this.animateDuration = 500;
    }
    
    onPressDisplayView()
    {
        if (this.state.isDisplay)
        {
            Animated.timing(this.state.animatedView, { toValue: 0, duration: this.animateDuration }).start(() => 
            { 
                this.setState({ isDisplay: false });
            });
        }
        else
        {
            Animated.timing(this.state.animatedView, { toValue: 100, duration: this.animateDuration }).start(() => 
            {
                this.setState({ isDisplay: true }); 
            });
        }
    }
    
    render()
    {
        return(
            <View style={{flex: 1}}>
                <Button onPress={() => {this.onPressDisplayView()}}>Display</Button>
                <View style={{ height: this.state.animatedViewInterpolate, backgroundColor: '#F00' }}>
                    <Text>HelloWorld!</Text>
                </View>
            </View>);
    }
    
    1. 使用插值
    2. 我没有运行就写了这个。也许工作与否:)

    【讨论】: