【问题标题】:Accessing Component method from outside the React app从 React 应用程序外部访问 Component 方法
【发布时间】:2016-08-09 08:17:54
【问题描述】:

我有一个 React/Redux 应用和一个组件。

不幸的是,我必须使用需要从 React 应用程序中触发函数的第三方库。

class Account extends React.Component {
  doSomething(){
    // Do react things
  }
  render{
    return()
  }
}

现在我有一些我无法控制的 HTML 被插入到 DOM 中。这不是 iFrame。

<button onClick="doSomething()">interact with react</button>

有什么方法可以从 React 外部触发 doSomething() 方法?我需要像ReactApp.Account.doSomething()这样的东西。

【问题讨论】:

标签: javascript reactjs scope redux


【解决方案1】:

如果我理解正确,在 React/Redux 应用程序中执行您想要的操作的正确方法是将新操作发送到商店并相应地注册您的事件处理。

<button onClick="store.dispatch(createAction())">interact with react</button>

除非万不得已,否则不要试图找到“破解” React 组件内部的方法。由于您已经有了类似 Flux 的模式,因此忽略它会很糟糕。尽管正如@Kovensky 在评论中提到的那样,这种方法的设置似乎稍微复杂一些。

【讨论】:

  • 如果他使用捆绑器,store 或 createAction 可能无法作为全局变量使用。他应该在window 中定义一个函数,由onclick 调用,以执行调度。
猜你喜欢
  • 1970-01-01
  • 2016-11-07
  • 2019-08-14
  • 1970-01-01
  • 1970-01-01
  • 2018-05-15
  • 2021-07-18
  • 1970-01-01
  • 2021-09-16
相关资源
最近更新 更多