美文网首页
React Portals

React Portals

作者: 三元一只十元三只 | 来源:发表于2020-04-10 09:42 被阅读0次

Protals用法: ReactDOM.createPortal(child, container)

看了官方文档中关于Portal事件冒泡的介绍,应该就是通过Protals, 子组件button中虽然没定义Click事件,但是能够通过Portals 被父组件所捕获并触发。

const appRoot = document.getElementById('app-root');

const modalRoot = document.getElementById('modal-root');

class Modal extends React.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 );

        }

}

class Parent extends React.Component {

        constructor(props) {

                super(props);

                this.state = {clicks: 0};

                this.handleClick = this.handleClick.bind(this);

        }

        handleClick() {

                this.setState(state => ({ clicks: state.clicks + 1 }));

        }

        render() {

                return (

                        <div onClick={this.handleClick}>

                        <p>Number of clicks: {this.state.clicks}</p>

                        <p> Open up the browser DevTools to observe that the button is not a child of the div with the onClick handler. </p>

                        <Modal>

                                <Child />

                        </Modal>

                       </div>

                );

         }

}

function Child() {

        return ( <div className="modal"> <button>Click</button> </div> );

}

ReactDOM.render(<Parent />, appRoot);

相关文章

网友评论

      本文标题:React Portals

      本文链接:https://www.haomeiwen.com/subject/rbklmhtx.html