[英]Accessing refs of a sibling component in React
在这种情况下,我有两个同级组件,第一个组件如下所示:
class X extends Component {
someRenderMethod(){
//does something
}
render(){
return(
<div class="xyz">
<p>some text</p>
<div class="the-div-i-want-render" ref="one">
{this.someRenderMethod}
</div>
</div>
)
}
}
function mapStateToProps(){
//
}
function mapDispatchToProps(){
//
}
export default connect(mapStateToProps, mapDispatchToProps)(X);
我的第二个兄弟组件如下:
import X from './x'
export class Y extends Component {
render(){
return (
<div>
<div>
//Here I want to render the div inside //component X
// In the real case, I show the div here in //response to a button click event.
//I have tried to import the component and get //the refs of X, but that is not working.
</div>
</div>
)
}
}
我尝试将组件X导入Y并获取X的引用,但这不起作用(ref对象始终为null)。 还有其他方法可以实现这一目标吗?
通过导入X
您只需导入组件的类。 不是它的实例( https://en.wikipedia.org/wiki/Class_(computer_programming) )
在安装组件(渲染一次)之前,组件refs
不可用。 因此,第一次访问refs
对象是在组件componentDidMount
生命周期函数中。
要解决您的问题:组件X
需要将其对树的refs
传达给父组件。 父级同时渲染X
和Y
挂载X
时,可以从父容器调用回调,并将refs
作为参数传递。 父级现在可以对此做出反应,并将refs
对象通过props
传递给Y
您可以使用本地状态this.state/setState
轻松完成X
安装后对Y
重新渲染。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.