首頁  >  文章  >  web前端  >  react中的portal是做什麼的

react中的portal是做什麼的

王林
王林原創
2020-11-27 10:02:411954瀏覽

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