【问题标题】:React Native StyleSheet global.js variable style errorReact Native StyleSheet global.js 变量样式错误
【发布时间】:2020-10-01 13:03:54
【问题描述】:

我不知道为什么,但我的应用不喜欢我为组件创建的样式表。在 index.js(顶级)中,我导入 global var import global from './src/global'; 然后我在 /src/styles.js 的 styles.js 文件中使用 global.width 设置为屏幕宽度(正确)。然后,我从 Styles 文件中导出各种样式,例如下面称为“按钮”的样式。最后在我的按钮组件中,我使用数组表示法来响应原生样式,为组件提供多个宽度(假设最高索引优先),但我只是得到一个错误。

导出的“按钮”样式表示例

...
padding: 12,
margin: 10,
//width: global.width/2.0,
alignSelf: "center",
marginTop: "auto",
...

按钮组件

      <TouchableOpacity
      onPress={this.props.onPress}
      style={[
        button.regularContainer,
        styles.localButtonStyle,
        this.props.style,
      ]}>
        <Text style={[
          button.regularText,
          styles.localTextStyle,
          this.props.textStyle,
        ]}>
          {this.props.title || 'Button'}
        </Text>
      </TouchableOpacity>

错误

Invariant Violation: [33,"RCTView",541,{"color":4278190080,"textAlign":"center","width":"<<NaN>>","backgroundColor":1308622847,"borderWidth":0,"borderColor":4294967295,"marginTop":40}] is not usable as a native method argument

如果我从与组件交互的三个样式表中的大多数中删除宽度元素,这些错误就会消失:button.regularContainerstyles.localButtonStylethis .props.style

global.js

import React from 'react';

import {
  Dimensions,
  Platform,
} from 'react-native';

let global: {
  HermesInternal: null | {}
};

global.width = Dimensions.get('window').width
global.height = Dimensions.get('window').height
global.ios = Platform.OS === 'ios'

export default global;

【问题讨论】:

    标签: react-native


    【解决方案1】:

    该错误看起来像是在尝试将 NaN(非数字)值分配给宽度。

    global.width/2.0 是否确定生成有效数字?

    我建议用实际数字替换变量的这种划分,看看是否仍然出现错误。

    【讨论】:

    • 我用百分比替换了每个 global.width 并且错误消失了......这不能帮助我理解为什么 global.width 不会产生有效数字。当我 console.log 变量时,它会产生一个数字。这令人沮丧。
    • 你能告诉我你是如何在你的 style.js 中初始化 global.width 变量的吗?
    • 感谢您查看此内容。抱歉回复慢。我更新了问题!
    • 我很困惑是什么导致了这个问题,你可以尝试在分配之前将 width 属性直接转换为一个数字。像这样:width: Number(global.width/2.0)
    • 它似乎真的只是进进出出这个错误——除非它仍然存在,否则我会将其标记为解决方案。另外,React 社区在堆栈上是否很小?我认为这个问题会有更多动静,尽管它是一个很长的帖子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 2016-10-10
    • 2018-02-26
    相关资源
    最近更新 更多