【问题标题】:React - Material UI Typography how to break long string to multiple linesReact - Material UI Typography 如何将长字符串分成多行
【发布时间】:2020-06-23 03:57:25
【问题描述】:

我正在使用 ReactJS 和名为 MaterialUI 的组件库。我的 Typography 组件有问题。

如果我写一个长文本,它会超出它的容器并且不会换行:

import React from "react";
import { Redirect } from "react-router";
import { withRouter } from "react-router-dom";

import Container from "@material-ui/core/Container";
import CssBaseline from "@material-ui/core/CssBaseline";
import Typography from "@material-ui/core/Typography";

function Homepage() {
  return (
    <div>
      <React.Fragment>
        <CssBaseline />
        <Container fixed>
          <Typography variant="h1" component="h2" align="center">
            123 456 789 qwertyuiopasdfghjklzxcvbnm
          </Typography>
        </Container>
      </React.Fragment>
    </div>
  );
}

export default withRouter(Homepage);

图片下方:

这发生在移动模式和桌面模式中。

您知道如何解决此问题吗?如果已达到容器的最大宽度,我希望将长词拆分为新行。

【问题讨论】:

    标签: javascript html css reactjs material-ui


    【解决方案1】:

    2021 年 11 月 24 日更新 createMuiTheme 已弃用 新版本的工作:

    const theme = createTheme({
        components: {
            MuiTypography: {
                styleOverrides: {
                    root: {
                        wordWrap: "break-word"
                    },
                },
            },
            MuiCard: {
                styleOverrides: {
                    root: {
                        width: "auto",
                        margin: 10,
    
                    },
                },
            },
        },
    });
    

    【讨论】:

      【解决方案2】:

      我遇到了这个问题,这是一个很好的解决方案。我最终将它全局添加到我的排版中。如果您需要这个,只需将 keikai 的答案添加到您的 createMuiTheme。

      //theme.jsx or theme.tsx
      import { createMuiTheme, responsiveFontSizes } from '@material-ui/core/styles';
      
      
      let theme = createMuiTheme({
        overrides: { 
          MuiTypography: { 
            root: { 
              wordWrap: "break-word"
            }
         } 
        }
      });
      
      export default theme;
      

      【讨论】:

        【解决方案3】:

        解决方案

        使用 word-wrap,它适用于 Material-UI 的排版。

        wordWrap: "break-word"
        

        参考:QA: wrap long string without any blank


        演示

        <Typography
          variant="h1"
          component="h2"
          align="center"
          style={{ wordWrap: "break-word" }}
        >
          123 456 789 qwertyuiopasdfghjklzxcvbnmdfsafasfasfadfaf
        </Typography>
        

        在线试用:

        【讨论】:

          猜你喜欢
          • 2013-05-13
          • 2020-07-18
          • 2011-09-01
          • 2019-03-14
          • 1970-01-01
          • 2021-05-29
          • 2019-08-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多