React中Portal的使用
import React from 'react';
import ReactDOM, { createPortal } from 'react-dom';
import './index.css';
// import App from './App';
// import Content from '../components/Dialog/Content';

class HelloFromPortal extends React.Component {
  render() {
    return (
      <div
        onClick={() => {
          alert('我爸应该知道我被点击了');
        }}
      >
        我是传送门里出来的Portal
      </div>
    );
  }
}

class AmISameAsPortal extends React.Component {
  render() {
    return (
      <div
        onClick={() => {
          alert('是不是传送门里出来呢?我知道被点击了');
        }}
      >
        是不是传送门出来的? not Portal
      </div>
    );
  }
}

class HelloReact extends React.Component {
  render() {
    return (
      <div>
        <h1>父组件</h1>
        <div
          onClick={() => {
            alert('YES  Dispaly');
          }}
        >
          {createPortal(
            <HelloFromPortal />,
            document.getElementById('another-root')
          )}
        </div>
        XXXX XXXX
        <div
          onClick={() => {
            alert('No display');
          }}
        >
          {ReactDOM.render(
            <AmISameAsPortal />,
            document.getElementById('another-container')
          )}
        </div>
      </div>
    );
  }
}

ReactDOM.render(<HelloReact />, document.getElementById('root'));

  

posted on 2021-05-25 21:34  人鱼之森  阅读(333)  评论(0编辑  收藏  举报