RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
react中portal的作用

小编给大家分享一下react中portal的作用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

创新互联公司于2013年创立,是专业互联网技术服务公司,拥有项目成都网站设计、成都做网站网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元郑州做网站,已为上家服务,为郑州各地企业和个人服务,联系电话:13518219792

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

作用:

将子组件渲染到非父组件的子树下,同时父组件仍能对子组件做出反应,我们甚至不用做过多的dom处理。

举例:

现在有两个组件,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 (
    <>
      
    
  );
}

以上是“react中portal的作用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!


网站题目:react中portal的作用
分享链接:http://scyingshan.cn/article/jgcoco.html