【问题标题】:Rendering a comma separated string of values in React Native在 React Native 中呈现逗号分隔的值字符串
【发布时间】:2021-01-03 06:32:51
【问题描述】:

我正在从 JSON 中提取 {item.dosage},它给了我以下字符串

"300gr short pasta, 2 spring onions, 50gr parmesan cheese"

我想在这样的单独文本行中显示以逗号分隔的每种成分

   300gr short pasta
   2 spring onions
   50gr parmesan cheese

我试图在我的 JSX 中执行以下操作

{item.dosage.map((step, i) => (
        <Text>
            {i > 0 && ", "}
               {step}
        </Text>
 ))}

我收到一个关于“未定义不是函数...”的错误。

【问题讨论】:

  • 什么是剂量?它包含什么?

标签: reactjs string react-native split array.prototype.map


【解决方案1】:

乍一看,它看起来越来越接近你所寻找的 这样你就可以根据需要为视图提供边距..

{item.dosage.split(', ').map((step, i) => (
  <View>
      <Text>
        {i > 0 && ", "}

         {step}
      </Text>
  </View>
 ))}

【讨论】:

  • 您的解决方案似乎不起作用,它仍然显示为没有逗号分隔的完整字符串。
  • item.dosage 包含什么。?我已经编辑了解决方案
  • 在本帖第一行评论"300gr short pasta, 2 spring onions, 50gr parmesan cheese"
【解决方案2】:
const str = "300gr short pasta, 2 spring onions, 50gr parmesan cheese"

...
<Text>
  {str.split(',').map((step)=> <Text>{step}{",\n"}</Text>)}
</Text>
...

// so try this way
<Text>
 {item.dosage.split(',').map((step)=> <Text>{step}{",\n"}</Text>)}
</Text>

【讨论】:

  • 虽然我需要使用split(", "){"\n"} 稍微调整代码,但它仍然有效。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-14
  • 1970-01-01
  • 2016-02-08
相关资源
最近更新 更多