Partial提供了一种将子组件渲染在父组件以外的DOM节点的方法,可是其行为和普通的 React 子节点行为一致。好比冒泡。因为 portal 仍存在于 React 树,且与 DOM 树中的位置无关,那么不管其子节点是不是 portal,像 context这样的功能特性都是不变的react
ReactDOM.createPortal(child, container)app
import React, { Component } from 'react'
import ReactDom from 'react-dom'
const modalRoot = document.getElementById('root');
class Partial extends Component {
constructor(props) {
super(props);
this.state = {
count: 1
}
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
console.log(this)
this.setState({
count: this.state.count + 1
})
}
render() {
return (
<div className="containner" onClick={this.handleClick}> <p>title</p> <p>you has click {this.state.count} times</p> <Modal> <Child /> </Modal> </div>
)
}
}
class Modal extends Component {
constructor(props) {
super(props);
this.el = document.createElement('div')
}
componentDidMount() {
modalRoot.appendChild(this.el)
}
componentWillUnmount() {
modalRoot.removeChild(this.el)
}
render() {
return ReactDom.createPortal(this.props.children, this.el)
}
}
function Child() {
return (
<div className="modal"> <button>click</button> </div>
)
}
export default Partial;
复制代码