首页 > 解决方案 > 如何在我的反应应用程序中获取我的谷歌自定义搜索输入

问题描述

我在我的 React 应用程序中使用 Google 自定义搜索:

http://www.assertivesolutions.ca

我想将默认占位符“自定义搜索”更改为其他内容。似乎没有办法用 CSS 做到这一点,所以我试图在 Javascript 中获取它。我在 componentDidMount() 钩子中有这个:

componentDidMount() {
    if (this.props.methodType === 'search') {
        const searchInput = document.querySelector('#gsc-i-id1');
        console.log('componentDidUpdate: ', searchInput);
    }
}

它将 null 打印到控制台,这意味着它没有从 DOM 中获取任何内容。

我不确定 Google 自定义搜索如何将搜索栏注入页面,但它似乎是异步的。因此,我不能指望它在 componentDidMount() 触发时准备好。但据我所知,componentDidMount 是页面加载时触发的最后一个钩子。

所以我的问题是:我如何知道 Google 自定义搜索何时准备就绪(即在 DOM 中可用)?有什么钩子可以用来抓住它吗?

谢谢。

这是完整的组件:

import React, { Component } from 'react';
import '../../App.scss';
import './ContactMethod.scss';
// eslint-disable-next-line
import callUsIcon from '../../assets/images/call-us-icon.png';

class ContactMethod extends Component {

componentDidMount() {
    if (this.props.methodType === 'search') {
        const searchInput = document.querySelector('#gsc-i-id1');
        console.log('componentDidUpdate: ', searchInput);
    }
}

render() {
    // Figure out which contact method this is:
    let methodTypeName = '';
    let methodTypeValue = '';
    let icon = '';
    switch (this.props.methodType) {
        case 'phone':
            methodTypeName = 'Call Us';
            methodTypeValue = '403-999-4951';
            icon = require('../../assets/images/call-us-icon.png');
            break;
        case 'email':
            methodTypeName = 'Email Us';
            methodTypeValue = 'support@assertivesolutions.ca';
            icon = require('../../assets/images/email-us-icon.png');
            break;
        case 'search':
            methodTypeName = 'Search';
            methodTypeValue = 'Enter search here...';
            icon = require('../../assets/images/search-icon.png');
            break;
        // need default case
    }

    // If this is search, we want an input field:
    var valueElement = <span className="contact-method-value">{ methodTypeValue }</span>;
    if (this.props.methodType === 'search') {
        valueElement = <div className="gcse-search" /> // <-- here
    }

    // Return the component:
    return (
        <div className="contact-method flex-row-space-between">
            <div className="flex-column-center">
                <img src={ icon } alt="{ icon }" />
            </div>
            <div className="name-and-value flex-column-space-around">
                <span className="contact-method-name">{ methodTypeName }</span>
                { valueElement } // <-- and here
            </div>
        </div>
    );
}
}

export default ContactMethod;

标签: javascriptreactjsreact-hooksgoogle-custom-search

解决方案


推荐阅读