React 中的排版 Material-UI

Typography in React Material-UI

我有这个文本框:

<Typography component="p" className={classes.text}>
        {this.props.post.text}
</Typography>

我希望能够包含段落,但输入的所有文本都会打印在一行中。

文档建议 paragraph 默认为 false 所以我必须将它设置为 `true.

我试过以下方法:

<Typography component="p" className={classes.text} paragraph="true">

我也试过:

<Typography component="p" className={classes.text} paragraph={true}>

这两个都不起作用,所以我的所有文本仍然打印成一行。

如何让段落显示?

附加信息: 据我现在的理解,排版中的 paragraph={true} 属性只是 adds a bottom-margin to the whole text。 IE。我的一个文本块是一个段落。如果我想要另一个段落,我将不得不添加另一个 Typography。类似于:

<Typography component="p" className={classes.text} paragraph={true}>
        {this.props.post.text}
</Typography>
<Typography component="p" className={classes.text} paragraph={true}>
        {this.props.post.text2}
</Typography>

这不是我想要的。也许我应该瞄准的是识别输入文本中的 return 字符。这是正确的吗?如果是这样,它是怎么做到的?

我试过这个:

  <pre>
    <Typography component="p" className={classes.text}>
      {this.props.post.text}
    </Typography>
  </pre>

标签保留标签内的空格和换行符。

虽然这不合适。如果我有长行,文本不会以卡片宽度换行。相反,任何超出卡片宽度的内容都会被截断。显然我想要这一切。我希望我的文字能够包裹在卡片中,并支持新行和新段落。这是怎么做到的?

这确实是一种奇怪的行为。据我所知,你做的一切都是正确的。 p 本身显示为块元素,因此默认情况下应按您希望的方式显示。但是,可能是您在 .text css class 中覆盖了它。试试看你有没有问题。如果没有,您可以随时使用变体 属性 variant="headline" 以便将它们放在新行上。

如果我做对了,您可以简单地利用 HTML 的强大功能并添加 <br /> 元素来插入换行符。

我想到了这个:

<Typography component="p" className={classes.text}>
  {this.props.post.text.split("\n").map((i, key) => {
    return <p key={key}>{i}</p>;
  })}
</Typography>

如果有更好的方法来做到这一点,我很想听听。

我试过你的答案,它完美地满足了我的需要。但是,控制台returns一个小错误

Warning: validateDOMNesting(...): <p> cannot appear as a descendant of <p>.

我通过将 .map() 中的 <p> 标记替换为 <Typography> 并将其全部包装在 <div> 中来稍微改进您的答案,如下所示:

<div className={classes.text}>
  {this.props.post.text.split('\n').map((i, key) => {
    return <Typography key={key} paragraph variant="body1">{i}</Typography>;
  })}
</div>

(您可以将 body1 替换为您想要的任何变体!)

这似乎消除了对我的警告,我希望能按您的预期工作。

新段落

<Typography>
  {this.props.text.split("\n").map((i, key) => {
    return <p key={key}>{i}</p>;
  })}
</Typography>

仅换行

<Typography>
  {this.props.text.split("\n").map((i, key) => {
    return <div key={key}>{i}</div>;
  })}
</Typography>

更好的方法是使用css的幂:

white-space: pre-line

如果您使用此 css 属性.

,将尊重“新行”字符

编辑:来自 Ionut-Alexandru Baltariu 的帮助

<Typography id="modal-description" sx={{ whiteSpace: 'pre-line'}}>

从 Material UI V5 开始,您现在可以访问许多 CSS 实用程序作为道具。对于空格,您现在可以执行以下操作:

<Typography whiteSpace="pre-line">{this.props.post.text}</Typography>