最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why can't we check a style attribute of a react-native app? - Stack Overflow

programmeradmin1浏览0评论

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]

why [1] returns false?

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]

why [1] returns false?

Share Improve this question asked Mar 7, 2017 at 10:30 Dinuka SalwathuraDinuka Salwathura 94417 silver badges34 bronze badges 5
  • 3 Show the full file. – Brigand Commented Mar 7, 2017 at 10:31
  • 2 what is return of console.log(styles.background)? – Banzay Commented Mar 7, 2017 at 10:32
  • @Banzay it was false – Dinuka Salwathura Commented Mar 7, 2017 at 10:34
  • @DinukaSalwathura which one is false? console.log(styles.background=='white') or console.log(styles.background')? – Hoang Hiep Commented Mar 7, 2017 at 10:38
  • If a style is inherited, I believe it won't show up under the element styles. Only if it is set explicitly on the element. Perhaps you can try using getComputedStyle if you have access to it. developer.mozilla/en-US/docs/Web/API/Window/… – jered Commented Mar 7, 2017 at 19:36
Add a ment  | 

2 Answers 2

Reset to default 8

In your case styles is a StyleSheet object.

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

 const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF'
    },
    wele: {
        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

To process a prop style of a ponent 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./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./a/35233409/1979861

Just want to make sure the parameter passing syntax is correct.
(Note: the square brackets surrounding the parameter are not needed.)

For single form style sheet:

var styleObj = StyleSheet.flatten(styles.container)

For multiple-form style sheet:

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

Then you can print it as a dict to exam the attributes:

console.log(styleObj)
发布评论

评论列表(0)

  1. 暂无评论