reactjs - 使用 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);
};
我很困惑,非常感谢任何关于我做错了什么的见解。
解决方案
嗯,它是这样工作的:
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
没有附加。
推荐阅读
- android - 谷歌地图主题
- php - MySQL/PHP 请求操作
- ruby-on-rails - 如何在 Rails 应用程序中使用私有 repo gem?
- node.js - 当我尝试在终端中执行 npm run dev 命令时出现 Npm 错误
- php - 如何在字段名称包含数字的模型中定义访问器?
- java - 在java中剪切变量路径
- go - 有没有办法通过使用 golang 标准库来格式化日志(如下所述)?
- websocket - 社交网络通知(web socket + service worker)
- visual-studio - 在 Visual Studio Team Services / Azure DevOps 中通过 FTP 在单一解决方案中部署多个站点
- excel - 在 Python 中拆分 Counter 得到的输出并推送到 Excel