【问题标题】:How to display nested labels in multiple lines?如何在多行中显示嵌套标签?
【发布时间】:2021-12-14 17:08:15
【问题描述】:

我尝试过使用 map 方法,就像我在研究如何做到这一点时看到的那样,但当我有如下结构时,它似乎不是要使用的方法:

const stepLabels = [
  { labels1: ['First One'] },
  { labels2: ['Second One', 'second One'] },
  { labels3: ['Third One', 'Third One', 'Third One'] }
];

我正在使用 Material UI Stepper 来尝试渲染下面的步骤标签

<Stepper alternativeLabel activeStep={2} connector={<StepConnector active completed classes={{ line: classes.connector, active: classes.activeConnector, completed: classes.activeConnector }} />} className={classes.stepper}>
        {steps.map(label => (
          <Step key={label}>
            <StepLabel classes={{ root: classes.stepLabelRoot }}>
              <span>
                { stepLabels.map(item => item.labels)}
              </span>
            </StepLabel>
          </Step>
        ))}
      </Stepper>

试图得到这个,在每个节点下方,它将显示标签。所以在第一个节点下面,它会说:

下面会显示第一个节点

First One

Second One 将在第二个节点下方显示两次

Second One
Second One

第三个节点会在第三个节点上显示三次

Third One
Third One
Third One

我已经尝试解决这个问题一个小时,但似乎找不到答案。

这样做真的很令人困惑,因为我确实知道如何使用 map 方法,但是这种结构有点令人困惑。我已经进行了反复试验,每次都会遇到不同的错误。像没有定义的东西等等。

【问题讨论】:

  • 你期望 span 元素的结果是什么?
  • 您希望嵌套数组['Third One', 'Third One', 'Third One']如何显示在步骤标签中?
  • 大家好,我已经更新了帖子以说明我的意思。如果还有什么不清楚的,请告诉我。谢谢!

标签: javascript arrays reactjs material-ui javascript-objects


【解决方案1】:

如果你想迭代并用它做一些事情,你需要在列表的所有元素中使用相同的属性名称。你的代码:

const stepLabels = [
  { labels1: ['First One'] },
  { labels2: ['Second One', 'second One'] },
  { labels3: ['Third One', 'Third One', 'Third One'] }
];

应改为:

const stepLabels = [
  { labels: ['First One'] },
  { labels: ['Second One', 'second One'] },
  { labels: ['Third One', 'Third One', 'Third One'] }
];

如果要添加换行符,可以添加br元素:

<Stepper alternativeLabel activeStep={2} className={classes.stepper}>
  {stepLabels.map((label) => (
    <Step key={label}>
      <StepLabel classes={{ root: classes.stepLabelRoot }}>
        {label.labels.map((item) => (
          <>
            {item}
            <br />
          </>
        ))}
      </StepLabel>
    </Step>
  ))}
</Stepper>

【讨论】:

  • 假设有1,2,3顺序是否可以使用索引label[labels${index+1}]
  • @cmgchess 索引是地图回调的第二个参数:labels.map((item, i) =&gt; labels[`labels${i+1}`])
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多