React入門0x015: Portal-如果可以更願意稱爲`容器`

0x001 Portal

先上栗子再說話:

class PortalComp extends React.Component {
    render() {
        return (
            <div>
                {this.props.children}
            </div>
        );
    }
}

class App extends React.Component {
    render() {
        return <PortalComp>
            hehe
        </PortalComp>
    }
}

ReactDom.render(
    <App/>,
    document.getElementById('app'))

如上的PortalComp就是一個Portal,寫在PortalComp中間的組件將被掛載到PortalCompprops.children,所以在PortalComp中可以使用props.children訪問。

Portal在英文中爲入口的意思,但是我更喜歡稱之爲容器,這不是音譯意譯,而是表譯。一個Portal組件看過去就像是一個容器啊,可以將子組件包裝起來,裝啥都行,就像一個垃圾桶。

0x002 實用栗子-通用Dialog

  • 源碼

    const DialogContainer={position:'absolute',left:'0',top:'0',width:'100%',height:'100%',backgroundColor:'rgba(0,0,0,0.5)'}
    const DialogContent={backgroundColor:'#ffffff',marginTop:'200px',width:'200px',marginLeft:'auto',marginRight:'auto',padding:'10px'}
    class Dialog extends React.Component {
        render() {
            return (
                <div style={DialogContainer}>
                    <div style={DialogContent}>
                        {this.props.children}
                    </div>
                </div>
            );
        }
    }
    
    class App extends React.Component {
        render() {
            return <div>
                <Dialog>
                    <p className='text-center'>這是一個dialog</p>
                    <div className='text-center'>
                        <button className='btn btn-primary'>確認</button>
                        <button  className='btn btn-danger'>取消</button>
                    </div>
                </Dialog>
            </div>
        }
    }
  • 效果

    clipboard.png

  • 說明:
    這樣,我們就寫出了一個通用的Dialog模版,只要將裏面的內容替換,就能做到不同的Dialog,比如替換成時間選擇器,那就是一個DateDialog

    class DateDialog extends React.Component{
        render() {
            return (
                <Dialog>
                    <p className='text-center'>請選擇時間</p>
                    <input type="date" className='form-control'/>
                    <div className='text-center mt-2'>
                        <button className='btn btn-primary'>確認</button>
                        <button  className='btn btn-danger'>取消</button>
                    </div>
                </Dialog>
            );
        }
    }

    效果如下:

    clipboard.png

    所以使用這種組合的方式將會衍生出無數的組件,彈窗時間選擇器、彈窗、Modal......太帥了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章