首页 > 解决方案 > 如何有条件地呈现逗号和句点?

问题描述

我有三个要有条件地渲染的项目,我希望能够在它们之间渲染逗号,如果是最后一个要渲染的东西,我希望能够渲染一个句点。

{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 时,第三个项目可能需要一段时间,等等。这似乎有很多条件要检查,我假设必须有一种更简单的方法来做到这一点?

标签: javascriptreactjsternary-operatorconditional-rendering

解决方案


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

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.');
}

我希望这对你有用。


推荐阅读