首页  >  文章  >  web前端  >  react中的portal是做什么的

react中的portal是做什么的

王林
王林原创
2020-11-27 10:02:411950浏览

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

react中的portal是做什么的

本文环境: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 (
      <div onClick={this.handleClick}>
        <p>The number of times a big dog barks: {this.state.bark}</p>
        <h3>Dog: </h3>
        <p>I can&#39;t see my children, but I can feel them</p>
        <Puppy>
          <Bully target={&#39;Puppy&#39;}/>
        </Puppy>
        <Bully target={&#39;Dog&#39;}/>
      </div>
    );
  }
}

ReactDOM.render(<Dog />, dogRoot);

再创建一个代替欺负Puppy的按钮组件

function Bully(props) {
  return (
    <>
      <button>Bully the {props.target}</button>
    </>
  );
}

相关推荐:js教程

以上是react中的portal是做什么的的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn