[英]React Material UI Grid align items conditionally to either left or right of screen
我正在創建一個聊天機器人並使用 React 和 Material UI。 我遇到了 Grid 組件的問題。 我正在嘗試將機器人消息與屏幕左側對齊,並將用戶消息對齊在屏幕右側,但是它不起作用。
我試過在 Grid 組件上使用 alignItems 道具,我也試過使用 CSS 屬性float='right'
和float='left'
。 但兩者似乎都不起作用。
我在下面有一個代碼沙箱鏈接,顯示了一個最小的可重現示例。 任何幫助將不勝感激。
https://codesandbox.io/s/react-chat-cuvfm?file=/src/App.js
預期輸出:所有藍色氣泡都應該在屏幕的右端
據我所知,如果消息的 ID = 0,那么它就是用戶消息。 然后,在您的ChatBubble
組件中,在 JSX 中添加
在 ChatBubble 中 style.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 添加到您的 bot(user) 消息來利用它,以將它們的內容( img + text )向右對齊
您可以在 ChatBubble/styles.js 中設置marginLeft: 'auto'
而不是使用float
屬性
這也會將用戶聊天氣泡的左邊距設置為盡可能大, marginRight
向收件人聊天氣泡添加marginRight
。 因此,您可以避免處理收件人的方向。
userChatBubbleOrientation: {
// float: "right",
marginLeft:'auto'
},
recipientChatBubbleOrientation: {
// float: "left"
// marginRight:'auto'
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.