【问题标题】:Access to component method in reactjs not working [duplicate]在reactjs中访问组件方法不起作用[重复]
【发布时间】:2018-05-07 04:38:55
【问题描述】:

我正在尝试从父组件访问子方法。这是子代码的样子

class child extends Component {

someMethod(v) {
// do something
}

render(){
return(
...
)
}
}

这是父代码

class Parent extends Component {
hoverOn(){
this._Child.someMethod(10);  // _Child is undefined here
}

render(){
return(
<div onMouseOver={this.hoverOn.bind(this)}>
<OtherChild ....>
<Child  ref={(Child) => { this._Child = Child; }} />
</div>
)
}
}

在 hoverOn() 时,我收到一条错误消息,告诉我 _Child 未定义。如何从父类调用 someMethod()?

【问题讨论】:

  • 嗯。诡异的。您的代码 sn-p 似乎是正确的。
  • 两件事,你的子组件类名是child,而它应该是Child,另一件事是因为你有onMouseOver事件,它可能在组件安装之前被触发,因此你可以得到一个错误,所以添加一个条件检查,比如this._Child &amp;&amp; this._Child.someMethod(10);

标签: reactjs


【解决方案1】:

尝试添加参考

class Parent extends Component {
hoverOn(){
    this.refs._Child.someMethod(10);
}}

【讨论】:

  • OP 使用文档中推荐的回调方法添加了一个 ref
  • OP 使用了比您建议的更好的方法。
  • 对不起,伙计们。没看到他用了回调方法
猜你喜欢
  • 2021-12-08
  • 2021-01-16
  • 2017-06-03
  • 1970-01-01
  • 2014-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-22
相关资源
最近更新 更多