【问题标题】:How to conditionally render commas and periods?如何有条件地呈现逗号和句点?
【发布时间】:2019-10-03 06:16:47
【问题描述】:

我有三个要按条件渲染的项目,我希望能够在它们之间渲染逗号,如果是最后一个要渲染的内容,则使用句点。

{this.state.a&&i++}    
{this.state.b&&i++}  
{this.state.c&&i++}                  
{this.state.a && (i==1?"item a.":"item a,")}
{this.state.b && (i==2?"item b.":"item b,")}
{this.state.c && (i==3?"item c.":"item c,")}

所以这显然不起作用,因为当 i=1 时,其他项目可能是唯一的项目,当 i=2 时,第三个项目可能需要一个句点,依此类推。它看起来像一个有很多条件要检查,我假设必须有更简单的方法来做到这一点?

【问题讨论】:

    标签: javascript reactjs ternary-operator conditional-rendering


    【解决方案1】:

    你可以在这里得到数组的帮助。

    const newArray = [];
    {this.state.a && newArray.push('item a')};
    {this.state.b && newArray.push('item b')};
    {this.state.c && newArray.push('item c')};
    
    if (newArray.length) {
      console.log(`${newArray.join(',')}.`);
    } else {
      console.log('No items present.');
    }
    

    我希望这对你有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-19
      • 1970-01-01
      • 2021-03-01
      • 1970-01-01
      • 2019-10-28
      • 2019-06-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多