【问题标题】:Why can't we check a style attribute of a react-native app?为什么我们不能检查 react-native 应用程序的样式属性?
【发布时间】:2017-03-07 10:30:50
【问题描述】:

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

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

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

为什么 [1] 返回 false?

【问题讨论】:

  • 显示完整文件。
  • console.log(styles.background) 的返回值是什么?
  • @Banzay 是假的
  • @DinukaSalwathura 哪个是假的? console.log(styles.background=='white')console.log(styles.background')?
  • 如果一个样式被继承,我相信它不会出现在元素样式下。仅当它在元素上显式设置时。如果您可以访问它,也许您可​​以尝试使用getComputedStyledeveloper.mozilla.org/en-US/docs/Web/API/Window/…

标签: javascript reactjs react-native


【解决方案1】:

在你的情况下,styles 是一个 StyleSheet 对象。

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

 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 样式,您可以如下使用它:

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

你可以在这里找到函数的源代码:

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

来源和更多详细信息:

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

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

【讨论】:

    【解决方案2】:

    只是想确保参数传递语法正确。
    (注意:参数周围的方括号不需要。)

    对于单一表单样式表:

    var styleObj = StyleSheet.flatten(styles.container)
    

    对于多表单样式表:

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

    然后您可以将其打印为 dict 以检查属性:

    console.log(styleObj)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-05
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多