【问题标题】:React Portal not generating children in functional componentReact Portal 未在功能组件中生成子级
【发布时间】:2020-06-24 15:56:49
【问题描述】:

我有简单的反应门户组件。首先我在类组件中写了这个,一切都很好。但我决定将其重写为功能组件。在此门户仅在 div#portal 内部生成 div 而在内部没有子级之后。我不知道哪里错了。

// Functional Component

import React, { useEffect } from 'react';
import { createPortal } from 'react-dom';

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

  useEffect(() => {
    portalRoot.appendChild(el);

    return () => portalRoot.removeChild(el);
  }, []);

  return createPortal(children, el);
};

export default Lightbox;

// Class component

// import { Component } from 'react';
// import ReactDOM from 'react-dom';

// const portalRoot = document.getElementById('portal');

// export default class Lightbox extends Component {
//   constructor() {
//     super();
//     this.el = document.createElement('div');
//   }

//   componentDidMount = () => {
//     portalRoot.appendChild(this.el);
//   };

//   componentWillUnmount = () => {
//     portalRoot.removeChild(this.el);
//   };
//   render() {
//     const { children } = this.props;
//     return ReactDOM.createPortal(children, this.el);
//   }
// }

【问题讨论】:

    标签: reactjs react-functional-component react-portal


    【解决方案1】:

    您在每次更新时都创建了const el = document.createElement('div');(因为它在主函数中),这是错误的。在 Class 组件中,您只在 constructor() 中创建了一次,所以每次它都在同一个 div 中,但在您的功能组件中,每次渲染/更新都会发生变化。

    您可以保留eluseRef() 之类的:

    const el = useRef(document.createElement('div')); 并将其用作el.current

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-11
      • 2021-07-29
      • 2022-11-22
      • 1970-01-01
      • 2019-12-08
      • 1970-01-01
      • 2020-01-22
      • 1970-01-01
      相关资源
      最近更新 更多