如何动态设置高度为动画后动画值的组件的高度?

Jim*_*Jim 7 reactjs react-native react-animated

目标:有一个下拉视图,可以随着时间的推移对高度扩展进行动画处理。需要注意的是:一旦视图展开,它需要能够动态处理是否存在其他视图数据。如果存在,将呈现一些额外的文本组件。

问题:就目前而言,动画将父级的高度设置为固定高度。因此,当 被additionalContent渲染时,它超出了父级的边界,而父级的高度是固定的。我不想明确设置父级的高度,因为这样我就无法按照我想要的方式为该方面设置动画。我想按原样维护高度动画,并动态调整父级的大小以在additionalContent存在时包含子级

const ListItem = (props) => {
    const [checkInModal, setCheckInModal] = useState(false);
    const [animatedHeight, setAnimatedHeight] = useState(new Animated.Value(0))
    const [animatedOpacity] = useState(new Animated.Value(0))
    const [dynamicHeight, setDynamicHeight] = useState(0);
    const [expanded, setExpanded] = useState(false);

    const toggleDropdown = () => {
        if (expanded == true) {
            // collapse dropdown
            Animated.timing(animatedHeight, {
              toValue: 0,
              duration: 200,
            }).start()

        } else {
            // expand dropdown
             Animated.timing(animatedHeight, {
              toValue: 100,
              duration: 200,
            }).start()
        }
        setExpanded(!expanded)
    }

    const renderAdditionalContent = () => {
      setDynamicHeight(75);

      if (someVariable == true) {
        return (
          <View> <Text> Some Content </Text> </View>
        )
      }
    }

    const interpolatedHeight = animatedHeight.interpolate({
        inputRange: [0, 100],
        outputRange: [75, 225]
    })

    const interpolatedOpacity = animatedOpacity.interpolate({
        inputRange: [0, 100],
        outputRange: [0.0, 1.0]
    })

    return (
        <Animated.View
            style={[styles.container, { height: interpolatedHeight + dynamicHeight }]}
        >
            <View style={{ flexDirection: 'row', justifyContent: 'space-between', }}>
                <View style={styles.leftContainer}>
                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                        <Text style={styles.title}>{props.title}</Text>
                    </View>
                    <Text style={styles.subtitle}>{time()}</Text>
                </View>

                <View style={styles.rightContainer}>
                    <TouchableOpacity onPress={() => toggleDropdown()} style={styles.toggleBtn}>
                        <Image source={require('../assets/img/chevron-down.png')} resizeMode={'contain'} style={styles.chevron} />
                    </TouchableOpacity>
                </View>
            </View>

            {expanded == true ? (
                <Animated.View style={[styles.bottomContainer, { opacity: interpolatedOpacity }]}>
                    <Components.BodyText text="Subject:" style={{ fontFamily: Fonts.OPENSANS_BOLD }} />

                    <Components.BodyText text={props.subject} />

                    { renderAdditionalContent() }

                </Animated.View>
            ) : null}
        </Animated.View>
    );
};

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#fff',
        borderRadius: 25,
        width: width * 0.95,
        marginBottom: 5,
        marginHorizontal: 5,
        paddingVertical: 15,
        paddingHorizontal: 15
    },
    leftContainer: {
        justifyContent: 'space-between',
    },
    rightContainer: {
        flexDirection: 'row',
        alignItems: 'center'
    },
    title: {
        fontFamily: Fonts.OPENSANS_BOLD,
        fontSize: 20,
        color: '#454A66'
    },
    subtitle: {
        color: '#454A66',
        fontSize: 14
    },
    typeIcon: {
        height: 25,
        width: 25
    },
    chevron: {
        height: 15,
        width: 15
    },
    toggleBtn: {
        borderWidth: 1,
        borderColor: Colors.PRIMARY_DARK,
        borderRadius: 7,
        paddingTop: 4,
        paddingBottom: 2.5,
        paddingHorizontal: 4,
        marginLeft: 10
    },
    bottomContainer: {
        marginVertical: 20
    },
    buttonContainer: {
        flexDirection: 'row',
        width: 250,
        justifyContent: 'space-between',
        alignSelf: 'center',
        marginVertical: 20
    },
    noShadow: {
        elevation: 0,
        shadowOffset: {
            width: 0,
            height: 0
        },
        shadowRadius: 0,
    }
});

export default ListItem;
Run Code Online (Sandbox Code Playgroud)

如何才能做到这一点?到目前为止,我尝试创建一个状态变量dynamicHeight并将其设置在呈现附加内容的函数内,但这还没有奏效。

这是零食: https: //snack.expo.io/P6WKioG76

澄清编辑:renderAdditionalContent 函数渲染附加内容(显然),该内容可以是从一行字符到多行的任何位置。无论字符数如何,组件的主要父容器都需要将所有子容器包含在其边界内。就目前而言,如果附加内容渲染的内容过多,内容将溢出组件的主要父容器的边框,这是必须避免的。显然,这可以通过简单地不给主要组件容器指定高度来完成。但想法是具有动画高度并正确包装子内容

有什么建议么?

Viv*_*shi 6

编辑:简单易行的方法

您还可以应用高度100%,这样我们就不需要计算内部内容的高度,它会根据提供的内容自动调整

const interpolatedHeight = animatedHeight.interpolate({
   inputRange: [0, 100],
   outputRange: ["0%", "100%"] // <---- HERE
})
Run Code Online (Sandbox Code Playgroud)

为了实现这一点,我<View>在 周围添加了标签<Animated.View>以获得100%正确的高度,并对 css 进行了一些更改,这看起来更优雅,并为您的问题提供了完美的解决方案。

工作演示


所以,你可以使用onLayout

计算出布局后立即触发此事件

第一步:

// setHeight 
const setHeight = (height) => {
    setDynamicHeight(prev => prev + height);
}

<View onLayout={(event) => {
    var { x, y, width, height } = event.nativeEvent.layout;
    setHeight(height); // <--- get the height and add it to total height
}}>
    <Text>Subject</Text>

    <Text>Subject Content</Text>

    {renderAdditionalContent()}
</View>
Run Code Online (Sandbox Code Playgroud)

第二步:

useEffect(() => {
    // trigger if only expanded
    if (expanded) {
        // trigger height animation , whenever there is change in height
        Animated.timing(animatedHeight, {
            toValue: dynamicHeight, // <--- animate to the given height
            duration: 200,
        }).start();
    }
}, [dynamicHeight]); // <--- check of height change
Run Code Online (Sandbox Code Playgroud)

工作演示(您可以通过添加删除文本来测试它)