react递归组件 无限弹窗

191 阅读1分钟

因业务需要写个聊天记录无限弹窗查看的功能 之前没怎么用过递归 这次学习到了分享在这里

先看代码

// 递归组件
export default function ChatHistoryModal({
  visibleModal,
  handleShowModal,
  compute = 0,
  currentList,
  onRefresh = () => {} }) {
  const [flag, setFlag] = useState(false);
  const [count, setCount] = useState(0);

  const listRef = useRef();
  const changeVisibModal = (item = false) => {
    setFlag(item);
  };
  const [previousList, setPreviousList] = useState([]);
  const fetchContext = async () => {
    const scrollerRef = listRef?.current?.scroller; // PullToRefresh
    const wrapperRef = scrollerRef?.current?.wrapperRef; // wrapper
    const sh = wrapperRef?.current?.scrollHeight;
    scrollerRef?.current?.scrollTo({
      y: (sh / 2) - (wrapperRef?.current?.clientHeight / 2),
      animated: false,
    });
  };
  useEffect(() => {
    if (visibleModal) {
      setCount(() => compute + 20);
      fetchContext();
    }
    // TODO 点开的聊天记录内容
    // console.log((currentList));
  }, [visibleModal]);
  return (
    <div>
      <Modal
        title="聊天记录"
        style={{ left: `${compute}px`, top: `${compute}px`, position: 'relative' }}
        centered
        className="modalContent"
        visible={visibleModal}
        mask={false}
        destroyOnClose
        footer={null}
        onCancel={() => {
          handleShowModal(false);
        }}
      >
        <Spin spinning={false} delay={40} tip="数据加载中,请稍后...">
          <div className="msgWrap">
            <IMChatList
              ref={listRef}
              dataSource={currentList}
              handleFalg={(msg) => {
                setFlag(true);
                setPreviousList(msg);
              }}
              onRefresh={onRefresh}
            />
          </div>
        </Spin>
        {flag ? (
          <ChatHistoryModal visibleModal={flag}
            handleShowModal={changeVisibModal}
            compute={count}
            currentList={previousList}
          />
        ) : null}
      </Modal>
    </div>
  );
}

使用方法

const [visibleModal, setVisibleModal] = useState(false);
const handleShowModal = (item = false) => {
    setVisibleModal(item);
  };
 // 最外层数据
const { currentChatList } = useSelector(state => ({
    currentChatList: state.im.currentChatList,
  }));

<ChatHistoryModal 
    visibleModal={visibleModal} 
    handleShowModal={handleShowModal} 
    currentList={currentChatList} />