如何在React JS中制作类似聊天气泡的聊天界面

4
我有一些 JSON 数据在 dummyData 中。我不确定如何根据 direction 将聊天气泡放置在左侧和右侧。我正在使用 Material UI 和 context API。参考图像。除了 Material UI 之外,我不想使用任何库。

enter image description here

目前,每个聊天气泡都位于左侧。如何根据direction定位气泡。到目前为止的代码(CodeSandbox):
    import React from 'react';
import makeStyles from '@material-ui/core/styles/makeStyles';

const useStyles = makeStyles(theme => ({
    container: {
        bottom: 0,
        position: 'fixed'
    },
    bubbleContainer: {
        width: '100%'
    },
    bubble: {
        border: '0.5px solid black',
        borderRadius: '10px',
        margin: '5px',
        padding: '10px',
        display: 'inline-block'
    }
}));

const ChatLayout = () => {
    const classes = useStyles();
    const dummyData = [
        {
            message: '1: This should be in left',
            direction: 'left'
        },
        {
            message: '2: This should be in right',
            direction: 'right'
        },
        {
            message: '3: This should be in left again',
            direction: 'left'
        }
    ];

    const chatBubbles = dummyData.map((obj, i = 0) => (
        <div className={classes.bubbleContainer}>
            <div key={i++} className={classes.bubble}>
                <div className={classes.button}>{obj.message}</div>
            </div>
        </div>
    ));
    return <div className={classes.container}>{chatBubbles}</div>;
};

export default ChatLayout;

2
我在你的codesandbox中进行了一些CSS和逻辑上的更改。请查看更新后的链接:https://codesandbox.io/s/practical-faraday-zmkdm-updated-zmkdm,https://zmkdm.csb.app/ - undefined
太完美了!请将其作为答案。我该如何将“bubbleContainer”对齐到底部?我尝试将“justify-content: flex-end !important”添加到“bubbleContainer”,但没有起作用。 - undefined
你是不是想让气泡从底部往上冒出来? - undefined
是的。我使用了"bottom: 0, position: 'fixed'"来实现这个功能。 - undefined
现在检查一下,我已经更新了style.css文件。 - undefined
1个回答

0

你可以创建一个独立的聊天气泡div并应用CSS。当你接收到消息时,将气泡div添加到你的用户列表中。


1
根据目前的写法,你的回答不够清晰。请编辑以添加更多细节,帮助其他人理解这如何回答所提出的问题。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接