首页 > 解决方案 > 使用 React Hooks 使用 Portal 为模态组件设置动画时出现问题

问题描述

当用户打开和关闭组件时,我正在尝试为我的模态组件设置动画。模态组件使用 Portal 在页面上挂载和卸载,我正在使用 react-transition-group 库中的 CSSTransitionGroup 来为挂载和卸载设置动画。

如果我为门户使用基于类的组件,那么一切都按预期工作。你可以在这里看到我的完整工作示例:https ://codepen.io/jeffcap1/pen/eoQZgp

这是作为类组件的门户片段:

const portalRoot = document.getElementById("portal");
class Portal extends React.Component {
    constructor(props) {
        super(props);
        this.el = document.createElement("div");
    }

    componentDidMount = () => {
        console.log("Portal componentDidMount!");
        portalRoot.appendChild(this.el);
    };

    componentWillUnmount = () => {
        console.log("Portal componentWillUnmount!");
        portalRoot.removeChild(this.el);
    };

    render() {
        const { children } = this.props;
        return ReactDOM.createPortal(children, this.el);
    }
}

但是,当我尝试更改 Portal 组件以使用新的 React Hooks API,特别是 useEffect 时,内容永远不会添加到页面上。您可以在此处查看完整示例:https ://codepen.io/jeffcap1/pen/YMRXxe

使用 Hooks 作为功能组件的 Portal 片段是:

const portalRoot = document.getElementById("portal");
const Portal = ({ children }) => {
const el = document.createElement("div");

React.useEffect(() => {
        console.log("Portal componentDidMount!");
        portalRoot.appendChild(el);
        return () => {
            console.log("Portal componentWillUnmount!");
            portalRoot.removeChild(el);
        };
    }, []); // eslint-disable-line react-hooks/exhaustive-deps

    return ReactDOM.createPortal(children, el);
};

我很困惑,非常感谢任何关于我做错了什么的见解。

标签: reactjsreact-hooks

解决方案


嗯,它是这样工作的:

const {useEffect, useMemo} = React;
const Portal = ({children}) => {
  const el = useMemo(() => document.createElement("div"), []);
  useEffect(() => {
    portalRoot.appendChild(el);
    return () => {
      portalRoot.removeChild(el);
    }
  }, []);
  return ReactDOM.createPortal(children, el);
}

笔:https ://codepen.io/anon/pen/OGaEbw

您正在创建el每个渲染而不是一次 - 这可能是问题所在,因为第二次渲染el没有附加。


推荐阅读