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;
複製代碼