react和react2
React 16, released in September 2017, introduced Portals.
2017年9月发布的React 16引入了Portal。
A portal is a way to render an element outside of its component hierarchy, in a separate component.
门户是一种在单独的组件中呈现其组件层次结构之外的元素的方法。
When that event is rendered, events happening on it are managed by the React components hierarchy rather than by the hierarchy set by the DOM position of the element.
呈现该事件时,发生在其上的事件由React组件层次结构管理,而不是由元素的DOM位置设置的层次结构管理。
Hence the name “portal”: an element sits somewhere in the DOM tree that’s outside of the normal React components tree, but the React component tree that includes it is still in charge.
因此,将其命名为“门户”:一个元素位于DOM树中某个位于正常React组件树之外的位置,但是包含它的React组件树仍在负责。
React offers an easy API to do this, ReactDOM.createPortal()
, which accepts 2 arguments. The first is the element to render, the second is the DOM element where to render it.
React提供了一个简单的API来实现这一点, ReactDOM.createPortal()
,它接受2个参数。 第一个是要渲染的元素,第二个是要在哪里渲染的DOM元素。
A classic use case for this is modal windows.
一个典型的用例是模式窗口。
A modal to render at full screen must live outside of the element, so it can be properly styled using CSS.
全屏渲染的模态必须位于元素外部,因此可以使用CSS对其进行适当的样式设置。
So if a modal is defined as a component:
因此,如果将模态定义为组件:
class Modal extends React.Component {
constructor(props) {
super(props)
this.el = document.createElement('div')
}
componentDidMount() {
document.getElementById('modal').appendChild(this.el)
}
componentWillUnmount() {
document.getElementById('modal').removeChild(this.el)
}
render() {
return ReactDOM.createPortal(
this.props.children,
this.el
)
}
}
We can have an App component render it, and all the events happening in the Modal component will be handled by App even though technically the modal is rendered in a different DOM tree:
我们可以有一个App组件来渲染它,并且Modal组件中发生的所有事件都将由App处理,即使从技术上来说,该模式是在不同的DOM树中呈现的:
class App extends React.Component {
constructor(props) {
super(props)
this.state = {showModal: false}
this.handleShow = this.handleShow.bind(this)
this.handleHide = this.handleHide.bind(this)
}
handleShow() {
this.setState({showModal: true})
}
handleHide() {
this.setState({showModal: false})
}
render() {
const modal = this.state.showModal ? (
<Modal>
<div>
The modal <button onClick={this.handleHide}>Hide</button>
</div>
</Modal>
) : ''
return (
<div>
The app <button onClick={this.handleShow}>Show modal</button>
{modal}
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'))
See the full example on https://codepen.io/flaviocopes/pen/KbdagX
请参阅https://codepen.io/flaviocopes/pen/KbdagX上的完整示例
react和react2