react 插槽(Portals)
前言:
昨天剛看了插槽,以為可以解決我工作中遇到的問題,非常激動,我今天又仔細想了想,發現並不能解決。。。 不過還是記錄一下插槽吧,加深印象,嗯,就醬。
插槽作用:
插槽即:ReactDOM.createPortal(child, container) ,由ReactDom提供的介面。 可以實現將子節點渲染到父元件DOM層次結構之外的DOM節點。
第一個引數(child
)是任何ofollow,noindex" target="_blank">可渲染的 React 子元素
,例如一個元素,字串或 片段(fragment)。第二個引數(container
)則是一個 DOM 元素。
應用場景:
對於 portal 的一個典型用例是當父元件有 overflow: hidden
或 z-index
樣式,但你需要子元件能夠在視覺上 “跳出(break out)” 其容器。例如,對話方塊、hovercards以及提示框。所以一般react元件裡的模態框,就是這樣實現的~
特點:事件冒泡
事件冒泡和普通react子節點一樣,是因為portal仍然存在於React tree中,而不用考慮其在真是DOM tree中的位置。嗯,這個特性很方便。
程式碼就上一些文件中的例子吧。。。
// These two containers are siblings in the DOM const appRoot = document.getElementById('app-root'); const modalRoot = document.getElementById('modal-root'); // Let's create a Modal component that is an abstraction around // the portal API. class Modal extends React.Component { constructor(props) { super(props); // Create a div that we'll render the modal into. Because each // Modal component has its own element, we can render multiple // modal components into the modal container. this.el = document.createElement('div'); } componentDidMount() { // Append the element into the DOM on mount. We'll render // into the modal container element (see the HTML tab). modalRoot.appendChild(this.el); } componentWillUnmount() { // Remove the element from the DOM when we unmount modalRoot.removeChild(this.el); } render() { // Use a portal to render the children into the element return ReactDOM.createPortal( // Any valid React child: JSX, strings, arrays, etc. this.props.children, // A DOM element this.el, ); } } // The Modal component is a normal React component, so we can // render it wherever we like without needing to know that it's // implemented with portals. 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() { // Show a Modal on click. // (In a real app, don't forget to use ARIA attributes // for accessibility!) const modal = this.state.showModal ? ( <Modal> <div className="modal"> <div> With a portal, we can render content into a different part of the DOM, as if it were any other React child. </div> This is being rendered inside the #modal-container div. <button onClick={this.handleHide}>Hide modal</button> </div> </Modal> ) : null; return ( <div className="app"> This div has overflow: hidden. <button onClick={this.handleShow}>Show modal</button> {modal} </div> ); } } ReactDOM.render(<App />, appRoot);
可以看到官例: 先寫了一個Modal元件,顯示Modal的props.children,在新建的插槽中。
本文到這裡就結束了!
最後隨手 講一下我為什麼昨天覺得可以解決我的問題,
我遇到的問題是:有一個容器,設定了overflow屬性;容器裡面一個一個的li,也就是列表;每一條的列表後面都有一個icon,懸浮會顯示一些額外資訊。 問題就是,由於外面設定了overflow,導致icon顯示的資訊,在靠近上下左右等位置 就就就顯示不出來了!!!哎,心塞塞啊~~本來以為這個插槽可以解決,可是,問題又來了,我插入到overflow 容器外面後,我就無法定位每一條的後面icon的位置了。。。
嗚嗚嗚。。。不忍了,哇哇哇!!!