react中portal的作用-創(chuàng)新互聯(lián)

小編給大家分享一下react中portal的作用,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

10年積累的成都網(wǎng)站設(shè)計、成都網(wǎng)站建設(shè)經(jīng)驗,可以快速應(yīng)對客戶對網(wǎng)站的新想法和需求。提供各種問題對應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識你,你也不認(rèn)識我。但先網(wǎng)站設(shè)計后付款的網(wǎng)站建設(shè)流程,更有昌寧免費網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。

react中的portal可以將子組件渲染到非父組件的子樹下,同時父組件仍能對子組件做出反應(yīng)。使用方法如【ReactDOM.createPortal(this.props.children, this.el);】。

作用:

將子組件渲染到非父組件的子樹下,同時父組件仍能對子組件做出反應(yīng),我們甚至不用做過多的dom處理。

舉例:

現(xiàn)在有兩個組件,Dog和Cat,我們想讓Dog的子組件Puppy放到Cat里,當(dāng)欺負Puppy的時候,即使相隔千里Dog也能感受到。

代碼實現(xiàn):

先獲取頁面中Dog窩和Cat窩

const dogRoot = document.getElementById("dog-house");
const catRoot = document.getElementById("cat-house");

創(chuàng)建一個Puppy組件

class Puppy extends React.Component {
  constructor(props) {
    super(props);
    // 創(chuàng)建一個容器標(biāo)簽
    this.el = document.createElement("div");
  }

  componentDidMount() {
  	// 把容器標(biāo)簽掛到 catRoot DOM下
    catRoot.append(this.el);
  }

  componentWillUnmount() {
    catRoot.removeChild(this.el);
  }

  render() {
  	// 利用portal把Puppy的內(nèi)容放到容器里
    return ReactDOM.createPortal(this.props.children, this.el);
  }
}

創(chuàng)建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>
        <h4>Dog: </h4>
        <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);

再創(chuàng)建一個代替欺負Puppy的按鈕組件

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

以上是“react中portal的作用”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

名稱欄目:react中portal的作用-創(chuàng)新互聯(lián)
文章地址:http://bm7419.com/article36/dgdcsg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT網(wǎng)站制作、網(wǎng)站策劃關(guān)鍵詞優(yōu)化、虛擬主機、動態(tài)網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)