![](/img/trans.png)
[英]Why are React components executed through the `React.createElement()` method?
[英]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.