获取对组件类实例的引用 [英] Getting a reference to the class instance of a component
问题描述
我有一个扩展 React.Component
的 typescript 类:
I have a typescript class that extends React.Component
:
class MyComponent extends React.Component<{}, {}>
{
constructor(props: {})
{
super(props);
}
public render()
{
return <span>Test</span>;
}
public MyMethod() {
console.log("Working fine");
}
}
然后有一个地方我必须手动创建一个实例并将其附加到DOM:
Then there is a place where I manually have to create an instance and attach this to the DOM:
var component = MyComponent;
var element = React.createElement(component, {}, null);
ReactDOM.render(element, myDomElementContainer);
由于系统的架构限制,我需要为该组件存储对我的类实例的引用以供以后使用,问题是我在创建的元素中找不到对我的类实例的任何引用,它只能通过属性 type
引用该类.
Due to architectural constraints of the system, I need to store a reference to my class instance for that component for later use, problem is that I can not find any reference to the instance of my class in the created element, it only have a reference to the class via the property type
.
React.createElement
只允许我提供类,而 ReactDOM.render
不喜欢手动实例化的对象.
React.createElement
is only allowing me to supply the class, and ReactDOM.render
does not like a manually instantiated object.
为了实例化自定义组件、将其附加到 DOM 并获取对组件类实例的引用,我应该怎么做?
What should I in order to instantiate a custom component, attach it to the DOM and get a reference to the instance of my component class?
推荐答案
您有几个选择:
(1) 使用 ReactDOM.render:
var element = ReactDOM.render(<MyComponent />, myDomElementContainer);
(2) 使用 React.createElement:>
(2) Use React.createElement:
var element = React.createElement(MyComponent);
ReactDOM.render(element);
(3) 使用 参考:
var element;
ReactDOM.render(<MyComponent ref={el => element = el } />, myDomElementContainer);
当 MyComponent
的实例被渲染后,该实例将被分配给 element
.
The instance will be assigned to element
when the instance of MyComponent
has been rendered.
这篇关于获取对组件类实例的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!