今天楼主遇到一种情况无论如何也无法通 this.refs.myComponent
拿到想要的元素. render 代码如下(使用了 react-bootstrap)
render : function(){
retrun (
<Modal.Dialog>
<Modal.Header>
<Modal.Title>Modal title</Modal.Title>
</Modal.Header>
<Modal.Body>
<MyComponent ref="myComponent" />
</Modal.Body>
</Modal.Dialog>
)
}
调试了半天才发现因为嵌套在其他 component 中这个 ref
已经不属于我这render
函数所在的 component 了. 所以我使用了另一种设置 component ref 的方法,叫做: The ref Callback Attribute
修改后的 render 方法. 然后就可以通过 this.myComponent
拿到相对应的 component 了
render : function(){
var that = this;
retrun (
<Modal.Dialog>
<Modal.Header>
<Modal.Title>Modal title</Modal.Title>
</Modal.Header>
<Modal.Body>
<MyComponent ref={function(comp){ that.myComponent = comp; } } />
</Modal.Body>
</Modal.Dialog>
)
}