简体   繁体   中英

React lifecycle method on createElement()

I want to store my components into an array to get further access to methods like addChild . I can't find a suitable lifecycle method to store the component. Right now I'm abusing the getInitialState function.

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
      });

    ...
  });
}

This function triggers only if the component is rendered. Is there a lifecycle function that is executed after the creation of a component with createElement() ?

Or is there a better way to store the component to get further access to methods?

You can get the instance of an element once it is rendered by providing a callback to the ref property of this element.

Here is how you could use it (I assumed you have a JSX and ES6 transpiler):

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}/>);

Here is a live version .

However, I would advise caution with such method as it can very rapidly become an anti-pattern. It is usually easier and more elegant to use the bottom-up re-render React mechanism. You just update the element's property from its parent and let React do the rest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM