react中的portal可以将子组件渲染到非父组件的子树下,同时父组件仍能对子组件做出反应;使用方法如【ReactDOM.createPortal(this.props.children, this.el);】。

本文环境:windows10、react16,本文适用于所有品牌的电脑。
作用:
将子组件渲染到非父组件的子树下,同时父组件仍能对子组件做出反应,我们甚至不用做过多的dom处理。
(学习视频分享:react视频教程)
举例:
现在有两个组件,Dog和Cat,我们想让Dog的子组件Puppy放到Cat里,当欺负Puppy的时候,即使相隔千里Dog也能感受到。
代码实现:
先获取页面中Dog窝和Cat窝
自从百度屏蔽淘宝客网站、淘宝抛弃淘宝客之后,个人站长集体陷入了恐慌之中。此时,什么值得买网的异军突起引起了广大个人站长的极大关注。做一个什么值得买一样的导购网站成了众多个人站长的一致心愿! TP-COUPON 导购系统 即是让个人站长实现此心愿的绝佳选择! 欢迎个人站长选用。V1.1版 更新记录:1.修正请求时查询淘宝店铺错误的bug2.删除一些无用的代码
0
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 (
<div onClick={this.handleClick}>
<p>The number of times a big dog barks: {this.state.bark}</p>
<h3>Dog: </h3>
<p>I can't see my children, but I can feel them</p>
<Puppy>
<Bully target={'Puppy'}/>
</Puppy>
<Bully target={'Dog'}/>
</div>
);
}
}
ReactDOM.render(<Dog />, dogRoot);再创建一个代替欺负Puppy的按钮组件
function Bully(props) {
return (
<>
<button>Bully the {props.target}</button>
</>
);
}相关推荐:js教程
以上就是react中的portal是做什么的的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号