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 RenderPortalV2 extends React.Component{
constructor(props){
super(props);
this.popup = document.createElement('div');
}
componentDidMount(){
//新建一个div标签并塞进body
document.body.appendChild(this.popup);
}
componentDidUpdate(){
}
componentWillUnmount(){//在组件卸载的时候,保证弹层也被卸载掉
ReactDOM.unmountComponentAtNode(this.popup);
document.body.removeChild(this.popup);
}
render(){
return ReactDOM.createPortal(
this.props.children,
this.popup
);
}
}
class Hello extends React.Component {
constructor(props){
super(props);
this.state={
showRenderInBodyV2:true,
}
}
render() {
return (
<div className="App">
<div className="RenderPortalV2" onClick={()=>{alert('RenderPortalV2 div 父元素冒泡事件')}}>
{this.state.showRenderInBodyV2 &&
<RenderPortalV2>
<p onClick={()=>{alert('RenderPortalV2 p 标签点击事件')}}> 我是RenderPortalV2</p>
</RenderPortalV2>
}
</div>
<button onClick={()=>{
this.setState({
showRenderInBodyV2:false,
})
}}>移除V2</button>
</div>
)
}
}
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);