【问题标题】:Trigger an action in another component through their parent in React通过 React 中的父组件触发另一个组件中的操作
【发布时间】:2019-12-31 09:34:20
【问题描述】:

有两个组件有一个父组件,我想通过它们的父组件触发另一个组件中的一个动作。到目前为止,我已经尝试过:

_mevent_show.js.jsx(组件之一):

gotoSearchPage() {
  this.props.gotoSearchPage()
},

return (
  <i className="fas fa-search"
      onClick={this.gotoSearchPage}>
  </i> )

_body.js.jsx(父)

gotoSearchPage() {
   this.calendar.changePropertyInCalendar()
},

render () {
  <Calendar mevents={this.state.mevents} ref={calendar => this.calendar = calendar}>
}

_calendar.js.jsx(应该触发其操作的其他组件)

changePropertyInCalendar() {
  this.setState({searchPage: true})
},

这些代码会产生类似this.calendar is null 的错误。我正在使用react-rails gem。有什么建议吗?谢谢

【问题讨论】:

  • 您确定this.calendar 存在吗?你可以发布你的父组件吗?您可能没有正确访问它,但我们需要更多信息来帮助您

标签: reactjs react-rails


【解决方案1】:

我看起来您的父组件 (_body) 没有控制 state,因为我可以看到 _calendar 组件正在处理 state 但它是子组件和父组件无法访问state。因此,您必须构建您的应用程序,因为父级是负责的并且是唯一可以更新 UI 的“状态”的应用程序,这也将通过 props 或 context 分发 values。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2020-09-18
    • 1970-01-01
    • 2020-01-09
    相关资源
    最近更新 更多