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组件仍可以通过点击改变父组件的数据,也可以向父组件传值。