Error: Invalid hook call - when calling a Modal component

Error: Invalid hook call - when calling a Modal component

当我尝试调用模态组件时出现此错误 -

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

如何在功能组件中按下按钮时显示此模态?
谢谢

Search.jsx

    import AddedToCart from '../modals/Modal';
    const Search=()=>{ 
    return(
              <div>
                  <button
                      onClick={() => AddedToCart()}
                    >
             </div>
         )

}

Modal.jsx

import Modal from 'react-bootstrap/Modal';
import React, { useState } from 'react';
export default function AddedToCart() {
  const [show, setShow] = useState(false);  
  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);

  return (
    <>
      <button variant='primary' onClick={handleShow}>
        Launch demo modal
      </button>

      <Modal show={show} onHide={handleClose}>
        <Modal.Header closeButton>
          <Modal.Title>Modal heading</Modal.Title>
        </Modal.Header>
        <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
        <Modal.Footer>
          <button variant='secondary' onClick={handleClose}>
            Close
          </button>
          <button variant='primary' onClick={handleClose}>
            Save Changes
          </button>
        </Modal.Footer>
      </Modal>
    </>
  );
}

任何帮助都会很棒。

   onClick={() => AddedToCart()}

您在点击处理程序中像函数一样调用它,这不是您在 React 中呈现内容的方式。

而是设置一个标志

   onClick={() => setOpenModal(true)}

然后在渲染中

{openModal && <AddedToCart/>}