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

本文环境:windows10、react16,本文适用于所有品牌的电脑。
作用:
将子组件渲染到非父组件的子树下,同时父组件仍能对子组件做出反应,我们甚至不用做过多的dom处理。
(学习视频分享:react视频教程)
举例:
现在有两个组件,Dog和Cat,我们想让Dog的子组件Puppy放到Cat里,当欺负Puppy的时候,即使相隔千里Dog也能感受到。
代码实现:
防封域名方法千千种,我们只做最简单且有用的这一种。微信域名防封是指通过技术手段来实现预付措施,一切说自己完全可以防封的那都是不可能的,一切说什么免死域名不会死的那也是吹牛逼的。我们正在做的是让我们的推广域名寿命更长一点,成本更低一点,效果更好一点。本源码采用 ASP+ACCESS 搭建,由于要用到二级域名,所以需要使用独享云虚机或者云服务器,不支持虚拟主机使用,不支持本地测试。目前这是免费测试版,
0
先获取页面中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 (
<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号