简体   繁体   English

react.js 在按钮点击时触发另一个组件内的事件

[英]react.js trigger event inside another component upon button click

I am building my first web app with react.我正在用 React 构建我的第一个 Web 应用程序。 Its a chat with multiple chat rooms.它与多个聊天室聊天。 This is what I got visually:这是我在视觉上得到的:

在此处输入图片说明

Now I simply want to click on "open" on any room and display the messages within that chatroom inside the white div on the right currently saying "HI MOM".现在我只想点击任何房间上的“打开”,并在右侧的白色 div 内显示该聊天室中的消息,当前说“嗨妈妈”。

But these two are different components.但这两个是不同的组件。

This is the list of chatrooms:这是聊天室列表:

export default function ChatRoomList({param1}) {
    const [chatRooms, setChatRooms] = React.useState([]);
    React.useEffect(()=>{
      (async () => {
          var x = await getChatRoom(param1)
          console.log(x)
          setChatRooms(x)
      })()
    },[])  
  
      return  (
          <div className='chatRoomView'>
               {chatRooms.map((chatRoom , index) => {
                  return (
                      <ul >
                        <li key={index}>
                            <table>
                                <tr>
                                    <td>
                                        ChatroomID: {chatRoom.chatIDFromTableChats}
                                        <br></br>
                                        Username:  {chatRoom.userNameUser2}
                                    </td>
                                    <td>
                                        <Button variant="contained" onClick={() => loadChatRoomFromID(chatRoom.chatIDFromTableChats)}>open</Button>
                                    </td>
                                </tr>
                            </table>
                        </li>
                      </ul>                   
                  )             
               })}
          </div>
      );
    }
  
    function loadChatRoomFromID(ID) {
       alert(`chatRoomID: ${ID}`);
    }

Upon button click I am currently just able to open an alert displaying the ID of the clicked element.单击按钮后,我目前只能打开显示所单击元素 ID 的警报。

Here is component two:这是组件二:

export default function ChatMessages() {

function loadMessages(ID){
    // HELP NEEDED?!
}

    return  <div class='mainChatView'>HI MOM</div>;
      
}

As you can see, there is a function called "loadMessages()" but it doesnt do anything since it needs to get the ID param passed and then start loading the messages of each room.如您所见,有一个名为“loadMessages()”的函数,但它没有做任何事情,因为它需要传递 ID 参数,然后开始加载每个房间的消息。

The connection from one to the other component is missing and so far, no answer i read about didnt fail miserably for me...从一个组件到另一个组件的连接丢失了,到目前为止,我读到的任何答案都没有让我悲惨地失败......

Can someone give me a working code example and explain what is happening?有人可以给我一个工作代码示例并解释发生了什么吗?

Thank you!谢谢!

In React, data can only be passed down from parent to child via props (see note at the end for more detail on this), not from sibling to sibling.在 React 中,数据只能通过 props 从父级传递到子级(有关详细信息,请参阅最后的注释),而不能从兄弟姐妹传递到兄弟姐妹。 This doesn't mean, however, that siblings cannot cause updates in each other, it just means that you need to restructure your code a bit so that data flows down properly.然而,这并不意味着兄弟姐妹不能导致彼此更新,这只是意味着您需要稍微重组您的代码,以便数据正确地向下流动。

You can store the active chatroom ID in the parent of the list and detail views and let the list view update the ID while the detail view uses the ID to load messages.您可以将活动聊天室 ID 存储在列表和详细信息视图的父级中,并让列表视图更新 ID,而详细信息视图使用 ID 加载消息。

Here's a simple example:这是一个简单的例子:

function Chat() {
    const [activeRoomID, setActiveRoomID] = React.useState(null);

    const onActiveChange = React.useCallback((id) => {
        setActiveRoomID(id);
    }, []);
    
    return (
        <div>
            <ChatRoomList onActiveChange={onActiveChange}/>
            <ChatMessages id={activeRoomID}/>
        </div>
    )
}

function ChatRoomList({ onActiveChange }) {
    // ...

    return (
        <div>
            {chatRooms.map(chatRoom => (
                <div key={chatRoom.chatIDFromTableChats}>
                    <div>ChatroomID: {chatRoom.chatIDFromTableChats}</div>
                    <Button onClick={() => onActiveChange(chatRoom.chatIDFromTableChats)}>Open</Button>
                </div>
            ))}
        </div>
    )
}

function ChatMessages({ id }) {
    // load messages for `id` and display
}

Notice that the data only flows down from the <Chat> component to its children.请注意,数据仅从<Chat>组件向下流向其子组件。

Note about data only flowing from parent to child: There are additional complexities to this statement.关于仅从父级流向子级的数据的注意事项:此语句还有额外的复杂性。 As this example shows, children can also pass data up to their parents but only by using a callback function provided via props, so the React-specific parts still only allow data to flow down.正如这个例子所示,孩子们也可以将数据传递给他们的父母,但只能使用通过 props 提供的回调函数,所以 React 特定的部分仍然只允许数据向下流动。 Also the context API allows for passing data to deep descendants (not just children).此外,上下文 API 允许将数据传递给深层后代(不仅仅是子代)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM