【问题标题】:React native dynamic style without re render the whole component反应原生动态样式而不重新渲染整个组件
【发布时间】:2017-07-17 00:58:35
【问题描述】:

下面的这种条件样式是否仍然适用于 react native?

style={[styles.base, this.state.active && styles.background]}

当组件挂载时,活动状态设置为false。

屏幕上有一个按钮可以将活动状态更改为 true。然后,我希望显示背景样式。但除非页面重新加载,否则情况并非如此。

有什么想法吗?

谢谢

【问题讨论】:

    标签: react-native stylesheet


    【解决方案1】:

    听起来您对使用 react-native 中的动画模块感兴趣。通过使用 Animated 模块,您可以拥有改变或动画的样式。您也可以使用 LayoutAnimation。您应该阅读Animation DocumentationLayoutAnimation documentation

    您可以从使用 LayoutAnimation 开始,看看它是否满足您的需求。设置起来很快!

    这是一个例子:

    import React, { Component} from 'react';
    import { View, LayoutAnimation, UIManager, Platform } from 'react-native';
    
    class MyComponent extends Component {
        constructor(props) {
            super(props);
    
            if (Platform.OS === 'android') {
                UIManager.setLayoutAnimationEnabledExperimental(true);
            }
        componentWillUpdate() {
            LayoutAnimation.spring() // automatimagically animates style changes
        }
        render() {
            <View style={[styles.base, this.state.active && styles.background]}>
            </View>
        }
    }
    

    【讨论】:

    • 谢谢。看起来像我需要的。我会试一试,然后告诉你。
    • 完美运行。谢谢!刚刚通过将 Platform 添加到 react-native 的导入来编辑您的答案。
    • 哦!我不敢相信我错过了! :)
    • @sbkl 我很高兴它对你有用!如果它对您有帮助,您是否介意赞成并接受答案?如果你用过 LayoutAnimation,你应该试试 Animated 模块。设置需要更多时间并且更复杂一些,但它可以为您提供更多控制权并让您为样式设置动画。
    猜你喜欢
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-07
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    相关资源
    最近更新 更多