React Base Fiddle (JSX)

Starting point for creating JSFiddles with React.

by panxiaoxian

HTML

<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

Babel + JSX

class RenderPortalV1 extends React.Component{
  constructor(props){
    super(props);
  }
  componentDidMount(){
    //新建一个div标签并塞进body
    this.popup = document.createElement('div');
    document.body.appendChild(this.popup);
    this._renderLayer();
  }
  componentDidUpdate(){
    this._renderLayer();
  }
  componentWillUnmount(){//在组件卸载的时候,保证弹层也被卸载掉
    ReactDOM.unmountComponentAtNode(this.popup);
    document.body.removeChild(this.popup);
  }
  _renderLayer(){//将弹层渲染到body下的div标签
    ReactDOM.render(this.props.children, this.popup);
  }
  render(){
    return null;
  }
}



class Hello extends React.Component {
  constructor(props){
    super(props);
    this.state={
      showRenderInBodyV1:true,
    }
  }
  
  render() {
    return (
       <div className="App">
        <div className="RenderPortalV1" onClick={()=>{alert('RenderPortalV1 div 父元素冒泡事件')}}>
          {this.state.showRenderInBodyV1 &&
              <RenderPortalV1>
                <p onClick={()=>{alert('RenderPortalV1 p 标签点击事件')}}> 我是RenderPortalV1</p>
              </RenderPortalV1>
          }
        </div>
        <button onClick={()=>{
          this.setState({
            showRenderInBodyV1:false,
          })
        }}>移除V1</button>
      </div>
    )
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);