为什么我们不能检查 react-native 应用程序的样式属性? [英] Why can't we check a style attribute of a react-native app?

查看:46
本文介绍了为什么我们不能检查 react-native 应用程序的样式属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查一个元素的颜色是否为白色,如下,

I wanted to check whether color is white of an element, as follows,

if(styles.background=='white')
console.log("ok")

console.log(styles.background=='white') --> was false [1]

为什么 [1] 返回 false?

why [1] returns false?

推荐答案

在你的例子中,styles 是一个 StyleSheet 对象.

In your case styles is a StyleSheet object.

您需要使用 StyleSheet.flatten 函数,如下所示:

You need to use the StyleSheet.flatten function as below:

 const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF'
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
    },
});

var styleObj = StyleSheet.flatten([styles.container])

console.warn(styleObj.backgroundColor==='#F5FCFF') //=>true

要处理组件的 prop 样式,您可以按如下方式使用它:

To process a prop style of a component you could use it as below:

 let backgroundColor = Stylesheet.flatten(this.props.style).backgroundColor;

您可以在此处找到该函数的源代码:

You can find the source code of the function here:

https://github.com/facebook/react-native/blob/master/Libraries/StyleSheet/flattenStyle.js

此处的来源和更多详细信息:

Sources and more details here:

https://facebook.github.io/react-native/docs/stylesheet.html

https://stackoverflow.com/a/35233409/1979861

这篇关于为什么我们不能检查 react-native 应用程序的样式属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆