react中的portal可以将子组件渲染到非父组件的子树下,同时父组件仍能对子组件做出反应;使用方法如【ReactDOM.createPortal(this.props.children, this.el);】。
本文环境:windows10、react16,本文适用于所有品牌的电脑。
作用:
将子组件渲染到非父组件的子树下,同时父组件仍能对子组件做出反应,我们甚至不用做过多的dom处理。
(学习视频分享:react视频教程)
举例:
现在有两个组件,Dog和Cat,我们想让Dog的子组件Puppy放到Cat里,当欺负Puppy的时候,即使相隔千里Dog也能感受到。
代码实现:
先获取页面中Dog窝和Cat窝const dogRoot = document.getElementById("dog-house");
const catRoot = document.getElementById("cat-house");
创建一个Puppy组件class Puppy extends React.Component {
constructor(props) {
super(props);
// 创建一个容器标签
this.el = document.createElement("div");
}
componentDidMount() {
// 把容器标签挂到 catRoot DOM下
catRoot.append(this.el);
}
componentWillUnmount() {
catRoot.removeChild(this.el);
}
render() {
// 利用portal把Puppy的内容放到容器里
return ReactDOM.createPortal(this.props.children, this.el);
}
}
创建Dog组件class Dog extends React.Component {
constructor(props) {
super(props);
this.state = { bark: 0 };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// 点击的时候 bark + 1
this.setState((state) => ({
bark: state.bark + 1,
}));
}
render() {
// 看上去Puppy组件是在Dog挂在Dog组件里,但其实它被挂载在其它地方
return (
The number of times a big dog barks: {this.state.bark}
Dog:
I can't see my children, but I can feel them
);
}
}
ReactDOM.render(, dogRoot);
再创建一个代替欺负Puppy的按钮组件function Bully(props) {
return (
<>
Bully the {props.target}
>
);
}
相关推荐:js教程