我正在為我的 Web 應用程式實作聊天,但我發現很難正確放置訊息,而且我不擅長 CSS。我想將所有者的訊息放在右側,將其他用戶的訊息放在左側。
這里有一些示例代碼:
// this is the container
<div className="container">
{messages.map(({ text='', isOwnMessage=false })=> <Message text={text} isOwnMessage={isOwnMessage}/>)}
</div>
// This is the message component
//...
<div classname="message">{text}</div>
<Message />如果isOwnMessage為false,我需要將組件放在左側,否則放在右側。我知道這可以通過提供絕對位置來完成,right:0但這對我不利。我也嘗試過:marginLeft: '50%'但是訊息本身的尺寸存在問題,最多為容器的 80%,否則就像它的內容一樣。
那么你會怎么做呢?
uj5u.com熱心網友回復:
我希望這有助于解決您的問題:
.message{
clear:both;
padding: 10px;
color: #eee;
}
.message.right{
background: green;
float:right;
}
.message.left{
background: cadetblue;
float:left;
}
<div class="container" >
<div class="message right">Owner message...</div>
<div class="message left">Response message...</div>
</div>
您可以Message像這樣實作組件:
<div classname=`message ${isOwnMessage ? 'right' : 'left'}`>{text}</div>
uj5u.com熱心網友回復:
通過使用align-selfflex 子級的屬性。
body {
font-family: sans-serif;
}
.conversation {
border: 1px solid black;
display: flex;
flex-direction: column;
gap: 0.2rem;
max-width: 300px;
padding: 0.5rem;
}
.message {
border-radius: 100vh;
padding: 0.5em 0.8em;
}
.self {
align-self: end;
background-color: #006aff;
color: white;
}
.other {
align-self: start;
background-color: gainsboro;
color: black;
}
<div class="conversation">
<div class="message other">hi</div>
<div class="message self">hello</div>
<div class="message other">what's up</div>
<div class="message self">i'm weekending</div>
<div class="message self">hbu</div>
</div>
uj5u.com熱心網友回復:
使用 flex 進行了這些更改。
.flex{
display:flex;
}
.flex-col{
flex-direction:column;
}
.ml-auto{
margin-left:auto;
}
// 零件
<div className="container flex flex-col">
{messages.map(({ text='', isOwnMessage=false })=> <Message text={text} isOwnMessage={isOwnMessage}
className={isOwnMessage?"ml-auto":""}
/>)}
</div>
// 這是訊息組件
<div classname={["message", props.className].join(" ")}>{text}</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/379688.html
