首页 文章

React Native - NSNumber无法转换为NSString

提问于
浏览
8

以下是我的反应组件的一部分 . 我有一个名为daysUntil的道具进入这个包含数字的组件 . 在这个例子中,它正在传递数字0,这导致fontWeight函数返回700

render: function() {
    return (
      <Text style={this.style()}>
       {this.props.day}
      </Text>
    )
  },
  style: function() {
    return {
      fontWeight: this.fontWeight()
    }
  },
  fontWeight: function() {
    var weight = 7 - this.props.daysUntil;
    return weight * 100;
  }

我收到以下错误:

NSNumber类型的JSON值'700'无法转换为NSSTring .

我假设这是因为font-weight期望值为字符串格式 . 对此有什么正确的解决方法?

先感谢您!

5 回答

  • 2

    在你的fontWeight()函数中

    return weight * 100;
    

    也许变成:

    var val= weight * 100;
    return val.toString();
    
  • 1

    fontWeight需要字符串值而不是整数 .

    只要确保你返回一个字符串:

    return (weight * 100).toString();
    

    确保您的“重量”变量不等于零 .

  • 1

    您可以使用 react-native 模块中的 StyleSheet ,如下所示:

    import StyleSheet from 'react-native'
    
    // declare the styles using Stylesheet.create
    const myStyles = StyleSheet.create({marginTop:30})
    
    //... some code inside render method
    
    <Text style={myStyles}>
            This is an example
    </Text>
    
  • 0

    我有一个类似的问题,我用图标而不是uri传递给图像 . 代码编写为接受 icon = 'path/to/icon'

    <Image source={{ uri: icon }}>
    

    但是我在传递 icon = require('path/to/icon') 并且我不得不将jsx切换到

    <Image source={icon}>
    
  • 16

    反应字体重量应该是一个字符串,

    在反应文件中他们特别提到 fontWeight enum('normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900') Specifies font weight. The values 'normal' and 'bold' are supported for most fonts. Not all fonts have a variant for each of the numeric values, in that case the closest one is chosen.

    所以你可以选择以下

    const boldText = {
      fontWeigth: '100'
    }
    

    要么

    const boldText = {
      fontWeight: 'bold'
    }
    

    在这段代码中你可以说

    style: function() {
        return {
          fontWeight: this.fontWeight()
        }
      },
      fontWeight: function() {
        var weight = 7 - this.props.daysUntil;
        return (weight * 100).toString();
      }
    

相关问题