【发布时间】:2019-09-14 04:32:15
【问题描述】:
我试图在用户打开和关闭组件时为我的模态组件设置动画。 modal 组件使用 Portal 在页面上挂载和卸载,我正在使用 react-transition-group 库中的 CSSTransitionGroup 为挂载和卸载设置动画。
如果我为 Portal 使用基于类的组件,那么一切都会按预期工作。你可以在这里看到我的完整工作示例:https://codepen.io/jeffcap1/pen/eoQZgp
这是作为类组件的 Portal sn-p:
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
Portal sn-p 作为使用 Hooks 的功能组件是:
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);
};
我很困惑,非常感谢任何关于我做错了什么的见解。
【问题讨论】:
标签: reactjs react-hooks