react-router-dom Link 点击关闭 bootstrap 模态 window

react-router-dom Link on click close bootstrap modal window

我需要通过单击 link 关闭模式 window。我的模态 window:

export const ModalWrapper = (props) => {
  const { children, title, modalName } = props;
  return (
    <div
      className="modal fade"
      id={`modal-${modalName}`}
      tabIndex="-1"
      role="dialog"
      aria-labelledby="modal-label"
      aria-hidden="true"
      style={{ display: 'none' }}
    >
      <div className="modal-dialog modal">
        <div className="modal-content" style={{ overflow: 'hidden' }}>
          <div className="modal-header">
            { title }
            <button type="button" className="close" data-dismiss="modal" aria-hidden="true">×</button>

          </div>
          <div className="modal-body" style={{ maxHeight: '435', overflowY: 'auto' }}>
            <ul className="list-unstyled todo-list">
              {children}
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
};

如何使用 react-router-dom Link 关闭 window?

它关闭 window 没有重定向:

<Link to="/registration" data-dismiss="modal" className="btn btn-default">Registration</Link>

它重定向但 window 没有关闭:

<Link to="/registration" className="btn btn-default">Registration</Link>

谢谢!

要实现您的目标,您可以:

您可以在他们的网站上阅读有关 React Bootstrap 库的更多信息。

如果你想避免额外的依赖,你可以使用 React 的 ref 功能:https://reactjs.org/docs/refs-and-the-dom.html 并用它来操作 dom(例如隐藏对话框 Link 单击或任何其他操作)。在这种情况下,只需将 ref 回调函数附加到对话框 dom 元素:

<div className="modal" ref={(input) => {this.input = input}}>
...

在这种情况下,您可以访问 dom 的 class 名称并从中删除 show class。请注意,您还必须从淡入淡出容器中删除显示(Bootstrap 生成的暗淡背景)。

我的总体建议是使用将隐藏当前模态并淡入淡出的实用函数。像:

const hideActiveModal = () => {
  const modal = document.getElementsByClassName('modal show')[0];
  const fade = document.getElementsByClassName('modal-backdrop show')[0];
  modal.className = modal.className.replace('show', '');
  fade.className = fade.className.replace('show', '');
};

结论: 你目前无法使用 clear React 隐藏 Bootstrap。使用 React-Bootstrap 或使用 util 函数(就像我提供的那样)。

作为更新,现在可以通过在 React Router V6 中监控路由器的位置并结合 useRef() 设置初始位置来解决此问题:

    const location = useLocation();
    const [showModal, setShowModal] = useState(true);

    const initialPage = useRef(location.pathname);

    useEffect(() => {
        if (location.pathname !== initialPage.current) {
            setShowModal(false);
        }
    }, [location]);

我正在使用 React Bootstrap,但对于您当前的实现,您可以更新相关的类名:

className={`modal ${showModal ? 'show', ''}`}

您还需要更新关闭按钮:

   onClick={() => {
      setShowModal(false);
   }}