如何在React组件中处理script.src URL回调? [英] How do you handle a script.src URL callback in a React component?

查看:261
本文介绍了如何在React组件中处理script.src URL回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法弄清楚如何根据Google脚本的GET请求触发函数.

I can't seem to figure out how to fire a function based off google's script GET request.

export class Map extends Component {

    constructor(props) {
        super(props);
        this.state = {};
    };

    componentDidMount = function () {
        console.log(google); // Uncaught ReferenceError: google is not defined
    };

    scriptInitialized = function () {
        console.log('scriptInitialized');
    };

    render() {

        let scriptInitialized = function () {
            console.log('scriptInitialized');
        };

        return (
            <div>
                <script type="text/javascript">/* nothing in here works */</script>
                <script src="https://maps.googleapis.com/maps/api/js?key=key&callback=scriptInitialized" defer async={true}/>
            </div>

        );
    }
}

我似乎无法使 callback = scriptInitialized 正常工作.如果将与src相关的所有JavaScript都保留在项目的index.html中,它将起作用,但这会使事情变得更加复杂.能够将内容集中在此组件上真是太棒了.

I can't seem to get callback=scriptInitialized to work. It works if I keep all the JavaScript related to the src in the index.html of my project but that makes things more complicated. It would be awesome to be able to keep things centralized to this component.

我知道Google地图有第三方库,但如果可能的话,我希望避免使用它们.

I know that there are third-party libraries for google maps but if possible I'd like to avoid them.

唯一的目的是在脚本加载完成后触发事件,这样我就可以使用它而无需触发"Uncaught ReferenceError:未定义google"..

The only goal of this is to fire an event when the script is finished loading so I can use it without firing off a "Uncaught ReferenceError: google is not defined".

推荐答案

来自Google api的回调正在寻找window.scriptInitialized.您将scriptInitialized绑定到组件,而不是窗口.这是有关如何添加功能的链接在React的窗口中

The callback from the google api is looking for window.scriptInitialized. You have the scriptInitialized tied to the component, not the window. Here is a link on how to add the function on the window in React

这篇关于如何在React组件中处理script.src URL回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆