简体   繁体   English

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

[英]React lifecycle method on createElement()

I want to store my components into an array to get further access to methods like addChild . 我想将组件存储到数组中,以进一步访问诸如addChild方法。 I can't find a suitable lifecycle method to store the component. 我找不到合适的生命周期方法来存储组件。 Right now I'm abusing the getInitialState function. 现在,我正在滥用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
      });

    ...
  });
}

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() ? 使用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. 通过提供对该元素的ref属性的回调,可以在呈现该元素后获得该元素的实例。

Here is how you could use it (I assumed you have a JSX and ES6 transpiler): 这是您如何使用它(我假设您有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}/>);

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. 使用自底向上的重新渲染React机制通常更容易,更优雅。 You just update the element's property from its parent and let React do the rest. 您只需从其父元素更新元素的属性,然后让React做其余的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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