react插槽Protal

react新出的react.createProtal可以将子组件挂载到任意的dom元素下面,还可以通过子组件来修改父组件的状态,react.createProtal(child,container),child是任何可渲染的react子元素,container是任意的dom元素,下面就看看这个例子

//父组件
 class Head extends Component{
    constructor(props){
        super(props)
        this.state = {clicks: 0};
    this.handleClick = this.handleClick.bind(this);
    }
    handleClick(e) {
         console.log(e.target.innerText)
        this.setState(state => ({
          clicks: state.clicks + 1
        }));
      }
    render(){
        return( <div onClick={this.handleClick}>
            <p>Number of clicks: {this.state.clicks}</p>
            <Modal>
              <Child />
            </Modal>
          </div>)
    }
}
//Modal组件
class Modal extends Component{
    constructor(props){
        super(props)
        this.div=document.createElement('div');
    }
    componentDidMount(){
        document.body.appendChild(this.div)

    }
    componentWillUnmount(){
        document.body.removeChild(this.div)
    }
    render(){
        return ReactDOM.createPortal(this.props.children,this.div)
    }
}
//子组件
function Child(){
    return (
        <div className="modal">
         <button>Click</button>
        </div>
      );
}

Modal组件主要是为子组件Child进行加工,这样Child组件就会挂载到Head组件的外面,但是Child组件仍可以通过点击改变父组件的数据,也可以向父组件传值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值