首页 > 解决方案 > 如何使用循环构建一个带有 in react 的句子?

问题描述

我想在网上打印出来。

【强制】创建账户即表示您同意ArticleA、ArticleB、ArticleC、... ArticleX。

其中 Link 是来自material-ui.

const createTACLine = (article, isMandatory) => {
  let cline = '';

  if (isMandatory) {
    cline = cline + '[Mandatory] By creating an account, you agree to ';
  }
  Object.keys(article).forEach(function (key) {

    cline = cline +  <Link
        component="button"
        variant="body2"
        to="/"
    > +{article[key].name}+ </Link>;
    if (parseInt(key) !== article.length - 1) {
      cline = cline + ', ';
    }

  });

  cline = cline + ".";

  return cline;
};

这里的文章在哪里

{
    "id": 12,
    "name": "ArticleA",
    "url": "http://.....",
},
{
    "id": 13,
    "name": "ArticleB",
    "url": "http://.....",
},
{
    "id": 13,
    "name": "ArticleC",
    "url": "http://.....",
},
{
    "id": 14,
    "name": "ArticleX",
    "url": "http://.....",
}

相反,我得到以下信息。

【强制性】创建账户即表示您同意[object Object]、[object Object]、[object Object]、[object Object]。

我看到很多使用 push 来推送列表项的示例,但我需要在这里构建一个句子。还有其他方法可以使用循环构建字符串吗?

标签: reactjs

解决方案


试试这个:

  createTACLine = (article, isMandatory) => {
    return (
      <div>
        {isMandatory ? "[Mandatory] By creating an account, you agree to " : ""}
        {article
          .map(art => {
            return (
              <Link component="button" variant="body2" to={art.url}>
                {art.name}
              </Link>
            );
          })
          .reduce((prev, curr) => [prev, ", ", curr])}
      </div>
    );
  };


推荐阅读