首页 > 解决方案 > 如何替换从 react-native 中的数组获得的字符串

问题描述

我需要用其他字符串替换字符串。我该如何更换?下面的代码仅更改 if 条件的第一条消息。我需要更改我需要的所有消息。

以下更改仅反映我的包里有书。”、“所有包里都有球”。其他如果不工作。(即)首先如果只有工作,其他人不工作。

代码:

renderMessages() {
  if (message.length > 2) {
     return (<Text>Available all sports items</Text>
  } else {
    return (
      this.state.validation.messages.map((msg) => {
        if (msg.indexOf('My bag contains books' > -1)) {
          let messagess = msg.replace("My bag contains books.", "All the bag have balls")
          return <Text style={{ fontSize: 13, color: 'red', marginBottom: 10, marginTop: 0 }}>{messagess}</Text>
        }
        if (msg.indexOf('My badminton bat' > -1)) {
          let messagess = msg.replace("My badminton bat", "Our basket balls")
          return <Text style={{ fontSize: 13, color: 'red', marginBottom: 10, marginTop: 0 }}>{messagess}</Text>
        }
        if (msg.indexOf('I have ball point pen' > -1)) {
          let messagess = msg.replace("I have ball point pen", "My pencils are in my bag")
          return <Text style={{ fontSize: 13, color: 'red', marginBottom: 10, marginTop: 0 }}>{messagess}</Text>
        } else {
          return (
            <Text style={{ fontSize: 13, color: 'red', marginBottom: 10, marginTop: 0 }}>
              {msg}
            </Text>
        }
      })
    )
  }
}

标签: javascriptreact-native

解决方案


您的代码中有两个错误(如最初发布的那样):

  1. 括号在您的所有匹配条件中都放错了位置:

    if (msg.indexOf('My bag contains books' > 0))
    

    应该:

    if (msg.indexOf('My bag contains books') > 0)
    
  2. 在这些相同的匹配条件下,您存在“一对一”的逻辑缺陷。它应该是

    if (msg.indexOf('My bag contains books') > -1)
    

    因为 Javascript 中的字符串索引,就像数组索引一样,从 0 开始。-1如果不匹配,则返回 String.indexOf。 > 0仅当您想忽略字符串开头的匹配项时才有意义。


推荐阅读