如何调用React组件's函数(Coherent UI)

How to call React component's function from a global context (Coherent UI)

本文关键字:Coherent UI 函数 组件 何调用 调用 React      更新时间:2024-06-04

我是React的新手,我正在尝试使用Coherent UI开发一个用于游戏引擎的UI。我的UI是用React构建的,我正试图将来自Coherent UI的消息导入我的React应用程序。

连贯的UI提供了向浏览器发送原始javascript脚本命令以执行或注册事件的能力,但这两种功能都不适用于我

我希望Coherent UI发送一个简单的javascript命令toggleLoadingAnimation();,但我不知道如何在我的React UI中创建这个javascript函数,它将实际调用组件的函数或更改其状态。

以下是Coherent UI关于发送Javascript命令的信息:https://coherent-labs.com/Documentation/cpp/dc/dc7/_binding_cxx.html

如何格式化命令或为要以这种方式调用的组件正确注册回调函数?

有没有任何方法可以告诉组件调用其成员函数之一?

这听起来像是React反模式,但您可能会考虑在componentDidMount内部定义一个函数:

componentDidMount() {
  var that = this;
  window.toggleLoadingAnimation = function () {
    that.whateverComponentMethodYouWant();
  }
}
componentWillUnmount() {
  window.toggleLoadingAnimation = undefined;
}

我最终使用Redux解决了这个问题,并在窗口级别公开了Store。

组件订阅存储(通常使用Redux的connect()自动订阅),然后可以发送调度消息,并由订阅的组件接收。

const store = createStore(Reducer, { variants, selectedVarient: 0, loadingVisible: false });
window.store = store;
...
<Provider store={ store }>
  <App />
</Provider>

这允许我从控制台发出命令(类似地,Coherent UI可以发送命令),如下所示:

store.dispatch({ type: 'SET_LOADING_VISIBLE', loadingVisible: true });

您可以更改道具,然后再次执行ReactDOM.render,react组件将保持状态。