簡體   English   中英

在createElement()上反應生命周期方法

[英]React lifecycle method on createElement()

我想將組件存儲到數組中,以進一步訪問諸如addChild方法。 我找不到合適的生命周期方法來存儲組件。 現在,我正在濫用getInitialState函數。

components = {};

function Component(){
  return React.createClass({
    getInitialState : function({
      components[this.props.id] = {addChild: this.addChild}; 
      return child : [];
    }),
    addChild(child){
      this.state.children.push(child);
      this.setState({
        children : this.state.children
      });

    ...
  });
}

僅在渲染組件時才觸發此函數。 使用createElement()創建組件后,是否存在生命周期函數?

還是有更好的方法來存儲組件以進一步訪問方法?

通過提供對該元素的ref屬性的回調,可以在呈現該元素后獲得該元素的實例。

這是您如何使用它(我假設您有JSX 和ES6轉譯器):

var instances = {};
const storeInstance = (i) => instances[i.props.id] = i;

var foo1 = (<Hello id="foo1" ref={storeInstance}/>);
var foo2 = (<Hello id="foo2" ref={storeInstance}/>);
var foo3 = (<Hello id="foo3" ref={storeInstance}/>);

這是現場版本

但是,我建議您謹慎使用這種方法,因為它會很快變成反模式。 使用自底向上的重新渲染React機制通常更容易,更優雅。 您只需從其父元素更新元素的屬性,然后讓React做其余的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM