第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

與多個(gè)組件反應(yīng)HOC

與多個(gè)組件反應(yīng)HOC

慕容3067478 2021-03-30 21:14:23
我想創(chuàng)建一個(gè)React HOC,理想情況下它將接收兩個(gè)組件而不是一個(gè)包裝的組件,并在它們之間切換。也就是說(shuō),在下面的代碼中,它們分別代替<h3>component one</h3>和<h3>component two<h3>代表子組件。我將如何做到這一點(diǎn)?有關(guān)如何編寫此HOC的一些偽代碼:<HOC>  <ComponentOne />  <ComponentTwo /></HOC><HOC  componentOne={<ComponentOne />}  componentTwo={<ComponentTwo />}/>hoc(componentOne, componentTwo)class HOC extends React.Component {    constructor() {    super();    this.state = {      onClick: false,    };    this.handleClick = this.handleClick.bind(this);  }  handleClick() {    this.setState({onClick: !this.state.onClick});  }      render() {    return (      <div>        <button onClick={this.handleClick}>Click Me!</button>        {           this.state.onClick ?            <h3>component one</h3> :            <h3>component two</h3>        }      </div>    );  }}ReactDOM.render(<HOC />, app);<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script><div id="app"></div>
查看完整描述

2 回答

?
海綿寶寶撒

TA貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊

如果一個(gè)組件有多個(gè)子代,this.props.children則將是一個(gè)數(shù)組。


class HOC extends React.Component {


    // ... rest of code ....


    render() {

        const { onClick } = this.state;

        const { children } = this.props;


        return !onClick ? children[0] : children[1];

    }

}

然后像這樣使用它:


<HOC>

    <div>Child One</div>   

    <div>Child Two</div>

</HOC>

顯然,這僅適用于兩個(gè)孩子,但是您可以通過(guò)將整數(shù)傳遞給<HOC>props來(lái)告訴它選擇哪個(gè)孩子來(lái)擴(kuò)展它。


編輯

快速瀏覽文檔后,這是我上面編寫的更好的版本,因?yàn)閠his.props.children它不是數(shù)組,而是一個(gè)不透明的數(shù)據(jù)結(jié)構(gòu):


class HOC extends React.Component {


    // ... rest of code ...


    render() {

        const { onClick } = this.state;

        const children = React.Children.toArray(this.props.children);


        return !onClick ? children[0] : children[1];

    }

}


查看完整回答
反對(duì) 回復(fù) 2021-04-08
?
qq_笑_17

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超7個(gè)贊

我不確定我是否理解你。為什么需要將它設(shè)為HOC?


如果您將組件作為道具傳遞:


<HOC

  componentOne={<ComponentOne />}

  componentTwo={<ComponentTwo />}

/>

然后,您將可以使用道具訪問(wèn)它們。


render() {

    return (

      <div>

        <button onClick={this.handleClick}>Click Me!</button>

        { 

          this.state.onClick ?

            this.props.componentOne :

            this.props.componentTwo

        }

      </div>

    );

   }


查看完整回答
反對(duì) 回復(fù) 2021-04-08
  • 2 回答
  • 0 關(guān)注
  • 185 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)