Bootstrap 无法使用flex:end,它对我不起作用[关闭]

63lcw9qa  于 2023-06-27  发布在  Bootstrap
关注(0)|答案(1)|浏览(152)

**关闭。**此题需要debugging details。目前不接受答复。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答这个问题。
9小时前关闭。
这篇文章是编辑并提交审查2小时前.
Improve this question
你好,我得到一个错误,而使用react js创建一个聊天消息应用程序,问题是,如果我是一个发送者,所以我的消息应该在右边,我收到的任何消息应该在左边,我尝试使用灵活的开始和灵活的结束条件,但它不工作
粘贴代码以及问题,基本上它是采取保证金从某处我检查了chatContainer css以及但它没有使用任何额外的空间任何一种保证金

请看一下,告诉我是什么错误,我已经试过了大部分的东西...谢谢
我的chatMesasage.js

import React from "react";
import { auth } from "./firebase";
import "./ChatMessage.css";
function ChatMessage({ message, time, sender }) {
  // console.log(auth?.currentUser.email);
  return (
    // <div
    //   className="chat-message snd "
    //   style={{
    //     // alignSelf:
    //     //   sender === auth?.currentUser.email ? "flex-end" : "flex-start",

    //     // backgroundColor:
    //     //   sender === auth?.currentUser.email ? "#dcf8c6" : "#fff",
    //     // float: sender === auth?.currentUser.email ? "right" : "",
    //     // flex: sender === auth?.currentUser.email ? "row" : "",
    //   }}
    // >

    <div
      className={`chat-message ${
        sender === auth?.currentUser.email ? "snd" : "rcv"
      }`}
    >
      <div className="chat-message-text">
        <p>{message}</p>
      </div>
      <div className="chat-message-date">
        <p>{new Date(time.toDate()).toLocaleString()}</p>
      </div>
    </div>
  );
}

export default ChatMessage;

我的chatContainer.js

import React, { useEffect, useState } from "react";
import "./ChatContainer.css";
import MoreVertIcon from "@mui/icons-material/MoreVert";
import InsertEmotIcon from "@mui/icons-material/InsertEmoticon";
import AttachFileIcon from "@mui/icons-material/AttachFile";
import SendIcon from "@mui/icons-material/Send";
import ChatMessage from "./ChatMessage";
import EmojiPicker from "emoji-picker-react";
import { useParams } from "react-router-dom";
import db from "./firebase";
import firebase from "firebase";

function ChatContainer({ currentUser }) {
  const { emailId } = useParams();
  const [message, setMessage] = useState("");
  const [openEmojiBox, setOpenEmojiBox] = useState(false);
  const [chatUser, setChatUser] = useState({});
  // const chatBox = useRef(null);
  const [chatMessages, setChatMessages] = useState([]);

  useEffect(() => {
    document.body.style.overflow = "hidden";
    const getUser = async () => {
      await db
        .collection("users")
        .doc(emailId)
        .onSnapshot((snapshot) => {
          setChatUser(snapshot.data());
        });
      //find that particular data whose id is this email id
    };
    const getMessages = async () => {
      await db
        .collection("chats")
        .doc(emailId)
        .collection("message")
        .orderBy("timeStamp", "asc")
        .onSnapshot((snapshot) => {
          let messages = snapshot.docs.map((doc) => doc.data());

          let newMessage = messages.filter(
            (message) =>
              message.senderEmail === (currentUser.email || emailId) ||
              message.receiverEmail === (currentUser.email || emailId)
          );
          setChatMessages(newMessage);
        });
    };
    getUser();
    getMessages();
  }, [currentUser.email]);
  const send = (e) => {
    e.preventDefault();
    if (emailId) {
      let payload = {
        text: message,
        senderEmail: currentUser.email,
        receiverEmail: emailId,
        timeStamp: firebase.firestore.Timestamp.now(),
      };
      // console.log(payload);
      //sender
      db.collection("chats")
        .doc(currentUser.email)
        .collection("message")
        .add(payload);
      //reciever
      db.collection("chats").doc(emailId).collection("message").add(payload);

      //add user to sender friend list
      db.collection("Friendlist")
        .doc(currentUser.email)
        .collection("list")
        .doc(emailId)
        .set({
          email: chatUser.email,
          fullname: chatUser.fullname,
          photoURL: chatUser.photoURL,
          lastMessage: message,
        });
      //add user to reciever friend list
      db.collection("Friendlist")
        .doc(emailId)
        .collection("list")
        .doc(currentUser.email)
        .set({
          email: currentUser.email,
          fullname: currentUser.fullname,
          photoURL: currentUser.photoURL,
          lastMessage: message,
        });
      setMessage("");
    }
  };

  return (
    <div className="chat-container">
      <div className="chat-container-header">
        <div className="chat-user-info">
          <div className="chat-user-img">
            <img src={chatUser?.photoURL} alt="" />
          </div>
          <p>{chatUser?.fullname}</p>
        </div>
        <div className="chat-container-header-btn">
          <MoreVertIcon />
        </div>
      </div>

      <div className="chat-display-container">
        <div>
          {chatMessages.map((message) => (
            <ChatMessage
              message={message.text}
              time={message.timeStamp}
              sender={message.senderEmail}
              currentUser={currentUser}
            />
          ))}
        </div>
      </div>

      <div className="chat-input">
        {openEmojiBox && (
          <div
            style={{
              bottom: "0",
              position: "absolute",
              top: "-450px",
            }}
          >
            {
              <EmojiPicker
                onEmojiClick={(emojiObject) =>
                  setMessage((message) => message + emojiObject.emoji)
                }
              />

              // <EmojiPicker onEmojiClick={(emojiObject)=> setMsg((prevMsg)=> prevMsg + emojiObject.emoji)}/>
            }
          </div>
        )}
        <div className="chat-input-btn" style={{ zIndex: "10" }}>
          <InsertEmotIcon
            onClick={(e) => {
              e.preventDefault();
              setOpenEmojiBox(!openEmojiBox);
            }}
          />
          <AttachFileIcon />
        </div>
        <form action="" method="get" onSubmit={send}>
          <input
            type="text"
            style={{ position: "relative" }}
            placeholder="Type a Message"
            value={message}
            // style={{ zIndex: "100" }}
            onChange={(e) => {
              setMessage(e.target.value); //we assign a value to the message, means updating the state
            }}
          />
        </form>
        <div className="chat-input-send-btn">
          <SendIcon onClick={send} />
        </div>
        {/* <div>
            <InsertEmotIcon />
            <AttachFileIcon />
          </div> */}
      </div>
    </div>
  );
}

export default ChatContainer;

我的聊天信息.csss

import React, { useEffect, useState } from "react";
import "./ChatContainer.css";
import MoreVertIcon from "@mui/icons-material/MoreVert";
import InsertEmotIcon from "@mui/icons-material/InsertEmoticon";
import AttachFileIcon from "@mui/icons-material/AttachFile";
import SendIcon from "@mui/icons-material/Send";
import ChatMessage from "./ChatMessage";
import EmojiPicker from "emoji-picker-react";
import { useParams } from "react-router-dom";
import db from "./firebase";
import firebase from "firebase";

function ChatContainer({ currentUser }) {
  const { emailId } = useParams();
  const [message, setMessage] = useState("");
  const [openEmojiBox, setOpenEmojiBox] = useState(false);
  const [chatUser, setChatUser] = useState({});
  // const chatBox = useRef(null);
  const [chatMessages, setChatMessages] = useState([]);

  useEffect(() => {
    document.body.style.overflow = "hidden";
    const getUser = async () => {
      await db
        .collection("users")
        .doc(emailId)
        .onSnapshot((snapshot) => {
          setChatUser(snapshot.data());
        });
      //find that particular data whose id is this email id
    };
    const getMessages = async () => {
      await db
        .collection("chats")
        .doc(emailId)
        .collection("message")
        .orderBy("timeStamp", "asc")
        .onSnapshot((snapshot) => {
          let messages = snapshot.docs.map((doc) => doc.data());

          let newMessage = messages.filter(
            (message) =>
              message.senderEmail === (currentUser.email || emailId) ||
              message.receiverEmail === (currentUser.email || emailId)
          );
          setChatMessages(newMessage);
        });
    };
    getUser();
    getMessages();
  }, [currentUser.email]);
  const send = (e) => {
    e.preventDefault();
    if (emailId) {
      let payload = {
        text: message,
        senderEmail: currentUser.email,
        receiverEmail: emailId,
        timeStamp: firebase.firestore.Timestamp.now(),
      };
      // console.log(payload);
      //sender
      db.collection("chats")
        .doc(currentUser.email)
        .collection("message")
        .add(payload);
      //reciever
      db.collection("chats").doc(emailId).collection("message").add(payload);

      //add user to sender friend list
      db.collection("Friendlist")
        .doc(currentUser.email)
        .collection("list")
        .doc(emailId)
        .set({
          email: chatUser.email,
          fullname: chatUser.fullname,
          photoURL: chatUser.photoURL,
          lastMessage: message,
        });
      //add user to reciever friend list
      db.collection("Friendlist")
        .doc(emailId)
        .collection("list")
        .doc(currentUser.email)
        .set({
          email: currentUser.email,
          fullname: currentUser.fullname,
          photoURL: currentUser.photoURL,
          lastMessage: message,
        });
      setMessage("");
    }
  };

  return (
    <div className="chat-container">
      <div className="chat-container-header">
        <div className="chat-user-info">
          <div className="chat-user-img">
            <img src={chatUser?.photoURL} alt="" />
          </div>
          <p>{chatUser?.fullname}</p>
        </div>
        <div className="chat-container-header-btn">
          <MoreVertIcon />
        </div>
      </div>

      <div className="chat-display-container">
        <div>
          {chatMessages.map((message) => (
            <ChatMessage
              message={message.text}
              time={message.timeStamp}
              sender={message.senderEmail}
              currentUser={currentUser}
            />
          ))}
        </div>
      </div>

      <div className="chat-input">
        {openEmojiBox && (
          <div
            style={{
              bottom: "0",
              position: "absolute",
              top: "-450px",
            }}
          >
            {
              <EmojiPicker
                onEmojiClick={(emojiObject) =>
                  setMessage((message) => message + emojiObject.emoji)
                }
              />

              // <EmojiPicker onEmojiClick={(emojiObject)=> setMsg((prevMsg)=> prevMsg + emojiObject.emoji)}/>
            }
          </div>
        )}
        <div className="chat-input-btn" style={{ zIndex: "10" }}>
          <InsertEmotIcon
            onClick={(e) => {
              e.preventDefault();
              setOpenEmojiBox(!openEmojiBox);
            }}
          />
          <AttachFileIcon />
        </div>
        <form action="" method="get" onSubmit={send}>
          <input
            type="text"
            style={{ position: "relative" }}
            placeholder="Type a Message"
            value={message}
            // style={{ zIndex: "100" }}
            onChange={(e) => {
              setMessage(e.target.value); //we assign a value to the message, means updating the state
            }}
          />
        </form>
        <div className="chat-input-send-btn">
          <SendIcon onClick={send} />
        </div>
        {/* <div>
            <InsertEmotIcon />
            <AttachFileIcon />
          </div> */}
      </div>
    </div>
  );
}

export default ChatContainer;
pdtvr36n

pdtvr36n1#

为什么不为我发送的聊天消息添加一个.snd类,为我收到的消息添加一个.rcv类,然后用CSS进行排序呢?
没有必要在每个发布的消息中重复标记style属性。只需要三个CSS规则:

/* CSS */
.chat-message { /* rules for all messages (sent and received) */ }
.rcv          { align-self: start }
.snd          { align-self: end }

除非'flexbox items'本身就是'flexbox containers',否则align-items: flex-end在flexbox child 上使用时将没有效果,因为它是flexbox parent 规则。
这是我在不使用框架的情况下能想到的最简单的例子:

/**************************/
/* Base flexbox structure */
/**************************/
.chat { display: flex; flex-direction: column }
.rcv  { align-self: start }
.snd  { align-self: end }

/******************/
/* Just eye-candy */
/******************/
*       { box-sizing: border-box }
body    { margin: 0; width: 100%; min-height: 100dvh }

.chat   { gap: 1rem; padding: 1rem; background-color: #ece5dd; min-height: 100dvh; }
.chat>* { display: grid; place-items: center; max-width: 85%; padding: 1rem; border-radius: 15px }

.rcv    { background-color: #dcf8c6 }
.snd    { background-color: White }
<div class="chat">
    <div class="rcv">...some received message...<br>Lorem ipsum dolor sit amet, exerci dolorem est ad. Sumo rebum prompta vim ad. Legendos expetendis id sed. Ex ius quem accusamus, pri et
        deleniti copiosae.</div>
    <div class="rcv">...some received message...<br>Cu vel debet nobis, repudiare deseruisse reprehendunt usu ad. Ex elit idque nam. Omnis munere detraxit mei te, eu labore appareat verterem
        est. Mel ex oporteat consectetuer.</div>
    <div class="snd">...some sent message...<br>Pro ea nonumy integre, mel at solum corpora. Id viris audiam repudiare cum, pri dolore appareat ex, per propriae detracto tacimates ex.
        Elitr sapientem quo et, usu suas porro tibique cu. Iusto causae eos et, tota principes interesset et eos. Similique intellegam cum ei, unum
        qualisque mel et, regione verterem delicatissimi qui ut. Aliquam incorrupte ea pro, vel veritus consequat id.</div>
    <div class="rcv">...some received message...<br>Pri te amet electram. Tation commodo minimum cu pri, utamur minimum id pri. No legimus atomorum vim. Vix id putent iuvaret salutandi, mel
        phaedrum conceptam ut.</div>
    <div class="snd">...some sent message...<br>Nam id utinam referrentur, similique intellegebat ad mel, eu nobis aeterno qui. Ad quodsi cetero sed, deserunt disputando nam an, veri
        viderer consetetur vel an. Zril vivendo pro no, oratio scripta quo eu, aeque elaboraret duo et. Ea nonumy essent sed, enim cetero pri an. An
        zril facete ius.</div>
</div>

相关问题