0

I would make a dynamic tabs chat using fluent ui for react.

Actually I'm showing content using a conditional switch that return chat content depending on tab item clicked.

Here's the switch condition

let switchTasks = (type, data) => {
  switch (type) {
    case "people":
      return <p>{data.content}</p>; // send basic text
    case "chat":
      return <ChatExample infos={data} />; // send component chat.
    default:
      break;
  }
};

In my chat component I set a state that I initialise with initial chat content ( should come from state) then I update every time I add a message.

const ChatExample = props => {
  const [inputValue, setInputValue] = React.useState("");
  const items = [
    {
      message: (
        <Chat.Message
          content="Hello"
          author="John Doe"
          timestamp="Yesterday, 10:15 PM"
          mine
        />
      ),
      contentPosition: "end",
      attached: "top",
      key: "message-id-1"
    },
    ...
  ];
  const [itemsChat, setItemsChat] = React.useState(items);

  const handleKeyDown = event => { // to add messages to chat.
    if (event.key == "Enter") {
      let elm = {
        message: (
          <Chat.Message
            content={inputValue}
            author="John Doe"
            timestamp="Yesterday, 10:15 PM"
            mine
          />
        ),
        contentPosition: "end",
        attached: "top",
        key: "message-id-1"
      };
      setItemsChat(itemsChat => [...itemsChat, elm]);
      setInputValue("");
    }
  };
  return (
    <div>
      <Chat items={itemsChat} />
      <ItemLayout
        content={
          <Input
            value={inputValue}
            onKeyDown={event => handleKeyDown(event)}
            onChange={event => setInputValue(event.target.value)}
            fluid
            clearable
            placeholder="Message..."
          />
        }
      />
    </div>
  );
};

Here's a demo of issue

My actual problem is that the chat content does not change when I select tab 2 or 3 (author name says at last tab selected after selecting tab 1 )

It does change content when I replace <Chat items={itemsChat} /> with <Chat items={items} />but in this case I'll not be able to add messages to chat (itemsChat represent items + new messages )

How can I make tabs updates chat content by keeping adding new messages to chat ?

4

1 回答 1

1

如果您为不同的数据“重用”相同的组件 [tree],您应该使用 differentntkey来强制重新渲染整个结构:

return <ChatExample infos={data} key={data.content}  />;
于 2020-05-19T04:45:46.583 回答