React Native - NSNumber 无法转换为 NSString

React Native - NSNumber cannot be converted to NSString

下面是我的反应组件的一部分。我有一个名为 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;
  }

我收到以下错误:

JSON value '700' of type NSNumber cannot be converted to NSSTring.

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

提前致谢!

在你的 fontWeight() 函数中

return weight * 100;

可能会变成:

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

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

只需确保 return 一个字符串:

return (weight * 100).toString();

还要确保您的 "weight" 变量不等于零。

您可以使用 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>

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

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

但我正在传递 icon = require('path/to/icon'),我不得不将 jsx 切换为

<Image source={icon}>

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

在 React 文档中,他们特别提到 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();
  }