首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在ReactJS中两个组件中传递相同道具的不同行为

在ReactJS中两个组件中传递相同道具的不同行为
EN

Stack Overflow用户
提问于 2022-02-14 10:43:18
回答 1查看 69关注 0票数 0

我把chatAppPropsApp.js -> ChatFeed.js那里传过来。

ChatFeed.js,我将相同的道具传递给两个组件,MessageForm.jsMyMessage.js

但是我可以在{...props}中使用MessageForm.js,但不能在MyMessage.js中使用。我想用道具上的{ chatId } = props

这是文件。

App.js

代码语言:javascript
复制
import "./App.css";
import { ChatEngine } from "react-chat-engine";
import ChatFeed from "./components/ChatFeed";
import LoginForm from "./components/LoginForm";

function App() {
  const project_id = process.env.REACT_APP_PROJECT_ID;

  if (!localStorage.getItem("username")) {
    return (
    <div className="w-full"><LoginForm /></div>
    );
  }

  return (
    <div>
    <ChatEngine
      height="100vh"
      userName={localStorage.getItem("username")}
      userSecret={localStorage.getItem("password")}
      projectID={project_id}
      renderChatFeed={(chatAppProps) => <ChatFeed {...chatAppProps} />}
      onNewMessage={() =>
        new Audio(
          "https://chat-engine-assets.s3.amazonaws.com/click.mp3"
        ).play()
      }
    />
    </div>
  );
}

export default App;

ChatFeed.js

代码语言:javascript
复制
import React from "react";
import MessageForm from "./MessageForm";
import MyMessage from "./MyMessage";
import TheirMessage from "./TheirMessage";

const ChatFeed = (props) => {
  const { chats, activeChat, messages, userName } = props; 

  const chat = chats && chats[activeChat];

  const renderReadReceipts = (message, isMyMessage) =>
      //some funvtion
    );

  const renderMessage = () => {
    const keys = Object.keys(messages);

    return keys.map((key, index) => {
      const message = messages[key];

      const lastMessageKey = index === 0 ? null : keys[index - 1];
      const isMyMessage = userName === message.sender.username;
      

      return (
        <div key={`msg_${index}`} style={{ width: "100%" }}>
          <div className="message-block">
            {isMyMessage ? (
              <MyMessage {...props} message={message} /> <!--Passing Props here but NOT working -->
            ) : (
              <TheirMessage
                message={message}
                lastMessage={messages[lastMessageKey]}
              />
            )}
          </div>
          <div
            style={{
              marginRight: isMyMessage ? "18px" : "0px",
              marginLeft: isMyMessage ? "0px" : "68px",
            }}
            className="read-receipts"
          >
            {renderReadReceipts(message, isMyMessage)}
          </div>
        </div>
      );
    });
  };

  if (!chat) return <div />;

  return (
    <div className="chat-feed">
      <div className="chat-title-container">
        <div className="chat-title">{chat?.title}</div>
        <div className="chat-subtitle">
          <strong className="font-bold">Members:</strong> {chat.people.map((item) => `${item.person.username}, `)}
        </div>
      </div>
      {renderMessage()}
      <div style={{ height: "100px" }} />
      <div className="message-form-container">
        <MessageForm {...props} chatId={activeChat} />  <!--Passing Props here AND working -->
      </div>
    </div>
  );
};

export default ChatFeed;

MessageForm.js

代码语言:javascript
复制
import React, { useState } from "react";
import { sendMessage, isTyping } from "react-chat-engine";

const MessageForm = (props) => {
  const [value, setValue] = useState("");

  const { chatId, creds } = props;
  //This is WORKING here , chat Id is seen here

  console.log("from message form= "+chatId);
  

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const project_id = process.env.REACT_APP_PROJECT_ID;



  const authObject = {
    "Project-ID": project_id,
    "User-Name": username,
    "User-Secret": password,
  };

  const handleSubmit = (e) => {
    e.preventDefault(); //to not do a browser refresh
    const text = value.trim();

    if (text.length > 0) sendMessage(creds, chatId, { text });

    setValue("");
  };

  const handleChange = (e) => {
    setValue(e.target.value);
    isTyping(props, chatId);
  };

  const handleUpload = (e) => {
    sendMessage(creds, chatId, { files: e.target.files, text: "" });
  };

  const handleLogout = () => {
    localStorage.removeItem("username", username);
    localStorage.removeItem("password", password);
    window.location.reload();
  }

  return (
    <form className="message-form" onSubmit={handleSubmit}>
      <div>
        <input
          className="message-input"
          placeholder="Send a Message ..."
          value={value}
          onChange={handleChange}
          onSubmit={handleSubmit}
        />
      </div>
      <div className="flex flex-row">
      <div>
        <label htmlFor="upload_button">
          <span className="image-button">
            <i className="far fa-image"></i>
          </span>
        </label>
        <input
          type="file"
          multiple={false}
          id="upload_button"
          className="hidden"
          onChange={handleUpload}
        />
        <button type="submit" className="send-button">
          <i className="far fa-paper-plane send-icon"></i>
        </button>
      </div>
      <div className="me-auto">
      <button onClick={handleLogout}  className="send-button">
          <i className="fas fa-power-off send-icon"></i>
        </button>
      </div>
      </div>
    </form>
  );
};

export default MessageForm;

MyMessage.js

代码语言:javascript
复制
import React from "react";
import { deleteMessage } from "react-chat-engine";

const MyMessage = ({ message }, props) => {
  const { chatId, creds } = props;
  // NOT working, chatId shows undefined
  
  console.log("from mymessage = "+chatId)  
 
  

  const handleDelete = (msgID) => {
    deleteMessage(props, chatId, msgID);
  };

  if (message?.attachments?.length > 0) {
    return (
      <img
        src={message.attachments[0].file}
        alt="message_attachment"
        className="message-image"
        style={{ float: "right" }}
      />
    );
  }



  return (
    <div
      className="message"
      style={{
        float: "right",
        marginRight: "18px",
        color: "white",
        backgroundColor: "#3B2A50",
      }}
    >
      {message?.text}
      <span>
        <button onClick={()=>handleDelete(message?.id)} className="bg-black text-red-800">
          Del
        </button>
      </span>
    </div>
  );
};

export default MyMessage;

我不知道为什么它们在传递相同的道具之后也会以不同的方式运行,并且在各自的组件中以相同的方式破坏。

EN

回答 1

Stack Overflow用户

发布于 2022-02-14 11:01:57

道具作为第一个参数传递给组件。在您的MyMessage组件中,您只需要从道具上销毁消息。取而代之的是这样做:

代码语言:javascript
复制
const MyMessage = (props) => {
  const { chatId, creds, message} = props;
  // ...

或者更好的是:

代码语言:javascript
复制
const MyMessage = ({chatId, creds, message}) => {
  // ...
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71110568

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档