【问题标题】:Unable to show/hide a component in a map function无法在地图功能中显示/隐藏组件
【发布时间】:2019-07-14 12:45:10
【问题描述】:

我有一个包含文本、值对的项目数组。仅当文本不为空且值从不为空且正常显示时,我才需要显示文本。

var items= [ 
  {id: 1, title: "title1", property: {text: null, value: 222}}, 
  {id: 2, title: "title2", property : {text: "star", value: 123}}, 
  {id: 3, title: "title3", property:{text: "sun", value: 456}}, 
  {id: 4, title: "title4", property: {text: null, value: 789}}
];

为此,我所做的是:

class DisplayItems extends Component {
  render() {
    return ({
      items.map(item => {
        return (
          showIf(!isEmpty(item.property.text))(
            <Text>
              text: {item.property.text}
            <Text />
          ),(
            <Text>
            value: {item.property.value}
            <Text />
          )
        )
      })
    })
  }
}

但问题是即使 item.property.text 为 null,它也会进入 showIf 条件,并且如果其中包含一些字符串,文本也不会被呈现。 showIf 是一个内部函数,如果条件为假,则隐藏组件。请帮助解决这个问题,因为我想呈现一个属性(文本)但无论条件如何都显示其他属性(值)。

【问题讨论】:

  • 你需要&amp;&amp;运营商

标签: javascript arrays react-native


【解决方案1】:

我认为问题在于第二个 return 语句。如果您仔细观察,那不是有效的 jsx。你应该把它改成这样:

class DisplayItems extends Component {

render() {
    return (

            { 
              items.map(item => {
                   return (
                            <Text>
                                 { showIf(!isEmpty(item.property.text))? "text: " + item.property.text : "text: " + item.property.value}
                            <Text/>
                         )
              })
            }
    )
}

}

【讨论】:

  • 我想渲染item.property.value,不管条件是成功还是失败
  • 问题是因为您在标签 中混合了文本和表达式。我已经更新了解决方案。希望这能解决您的问题。
【解决方案2】:

也许这可以为你解决:

class DisplayItems extends Component {

render() {
    return (
            { 
              items.map(item => {
                    return (
                          <Text>
                              { item.property.text && `text: ${item.property.text}` }
                              value: {item.property.value}
                          <Text/>
                      )
                });
            }
        )
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 2018-08-29
    • 2021-09-30
    • 1970-01-01
    • 2018-07-09
    • 2012-06-06
    相关资源
    最近更新 更多