React Native - NSNumber无法转换为NSString

问题描述 投票:9回答:5

以下是我的反应组件的一部分。我有一个名为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期望值为字符串格式。对此有什么正确的解决方法?

先感谢您!

ios reactjs nsstring react-native nsnumber
5个回答
16
投票

在你的fontWeight()函数中

return weight * 100;

也许变成:

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

4
投票

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

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

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

<Image source={icon}>

2
投票

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

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

return (weight * 100).toString();

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


1
投票

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

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
投票

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

在反应文件中,他们特别提到了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();
  }
© www.soinside.com 2019 - 2024. All rights reserved.