如何让Qt WebEngine调用反应组件功能

时间:2019-05-14 08:32:33

标签: reactjs qt antd

我遇到了问题   RunJavaScript4 api无法调用函数,当我单击按钮时,通过react绑定页面渲染中的js函数。控制台日志功能goOnPkg未定义

qt版本5.10

转到文件中的代码:

channel := webchannel.NewQWebChannel(nil)
channel.RegisterObject("pkgBridge", qmlBridge)
wv.Page().SetWebChannel2(channel)
qmlBridge := NewQmlBridge(nil)
qmlBridge.ConnectSendToGo(func(data string) string {
  ap.WebView.Page().RunJavaScript4(fmt.Sprintf("%s('%s')", funcName, data))
})

react组件中的代码:

export  function go0nPkg(id) {
    console. log("golang can' t call this function successfully") ;
    console. log(id);
}

@Form.create()
class PkgDoPkgList extends React Component {
constructor(props) 
componentDidMount( ) {}
handlePkgBtnClick = (id, actionId, action) => {
let action_obj = { "action": action, "action_id": actionId};
let action_json = JSON.stringify(action_obj );

new QWebChannel(qt.webChannelTransport, function (channel)  {
    pkgBridge = channel.objects.pkgBridge;
    window.bridge = pkgBridge;
    window.bridge.sendToGo(action_json);
}
render() {}
export default PkgDoPkgList;

golang无法成功响应组件中的函数。 -_-!

1 个答案:

答案 0 :(得分:0)

啊哈,我解决了这个问题。

  1. 在js文件中,我们应该将React Class实例导出到窗口。
import xxx;

//...

window.updateValue = function(url) {
    alert("call ok !");
    // if(window.callback != undefined) {
    //    window.callback.updateValue(url);
    // }
};

window.setCallback = function(callback) {
    window.callback = callback;
}

//...

export default class MyFeedback extends React.Component {

   //...
   // key step
   //  in react life cycle `componentWillMount` set `this` :
   componentWillMount() {
         window.setCallback(this);
   }

  //...

}

  1. 在go文件中,我们这样调用函数:
ap.WebView.Page().RunJavaScript4("window.updateValue('hello')")

运行项目后。我看到警报call ok!

Refer to the link : https://blog.csdn.net/ZHOUYONGXYZ/article/details/82760929