【问题标题】:React Material UI Grid align items conditionally to either left or right of screenReact Material UI Grid 有条件地将项目对齐到屏幕的左侧或右侧
【发布时间】:2021-09-12 21:43:00
【问题描述】:

我正在创建一个聊天机器人并使用 React 和 Material UI。我遇到了 Grid 组件的问题。我正在尝试将机器人消息与屏幕左侧对齐,并将用户消息在屏幕右侧对齐,但是它不起作用。

我尝试在 Grid 组件上使用 alignItems 属性,我也尝试使用 CSS 属性 float='right'float='left'。但两者似乎都不起作用。

我在下面有一个代码沙箱链接,显示了一个最小的可重现示例。任何帮助将不胜感激。

https://codesandbox.io/s/react-chat-cuvfm?file=/src/App.js

电流输出:

预期输出: 所有的蓝色气泡都应该在屏幕的右端

【问题讨论】:

    标签: javascript css reactjs material-ui


    【解决方案1】:

    据我所知,如果消息的 ID = 0,那么它就是用户消息。然后, 在您的 ChatBubble 组件中,在 JSX 中添加

    在 ChatBubble styles.js 中

      userChatBubbleOrientation: {
        justifyContent: "flex-end"
      },
      recipientChatBubbleOrientation: {
        justifyContent: "flex-start"
      } 
    

    在 ChatBubble 组件中

      const chatBubbleOrientationStyles =
        props.message.id === 0
          ? {
              ...styles.userChatBubbleOrientation
            }
          : {
              ...styles.recipientChatBubbleOrientation
            };
    
    <Grid
      container
      style={chatBubbleOrientationStyles}
    >
    

    使用flexbox 而不是浮点数。切勿将浮动用于布局目的。此外,Material UI 使用 flexbox,因此可以通过将 justifyContent:flex-end 添加到您的机器人(用户)消息来使用它,以将它们的内容(img + text)对齐到右侧

    【讨论】:

    • 感谢它的工作,我已经更新了代码沙箱链接,以便它可以帮助其他人。
    • 我还要求编辑您的答案,以修复与沙箱相比变量命名不一致的问题。
    • 你能解释一下为什么我们不应该使用浮点数吗?
    • @dracarys 如此处所述developer.mozilla.org/en-US/docs/Web/CSS/float 该元素已从页面的正常流程中删除,但仍是流程的一部分。在 flexbox 和 cssgrid 出现之前,它被大量使用,因为没有其他解决方案。但是现在它主要用于当您想在图像周围包装一些文本时(例如在 float:left 中;我共享的 mdn 链接中的示例)。另外,就像我在回答中所说的那样,Material UI 基于 flexbox 布局。那么为什么不使用它呢?
    【解决方案2】:

    您可以在 ChatBubble/styles.js 中设置 marginLeft: 'auto',而不是使用 float 属性

    这也会为用户聊天气泡设置尽可能大的左边距,无需将marginRight 添加到收件人聊天气泡中。因此,您可以避免处理收件人的方向。

      userChatBubbleOrientation: {
        // float: "right",
        marginLeft:'auto'
      },
      recipientChatBubbleOrientation: {
        // float: "left"
        // marginRight:'auto'
      },
    

    【讨论】:

      猜你喜欢
      • 2020-09-05
      • 2015-03-17
      • 1970-01-01
      • 2019-11-10
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      相关资源
      最近更新 更多