javascript - 如何在我的反应应用程序中获取我的谷歌自定义搜索输入
问题描述
我在我的 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;
解决方案
推荐阅读
- javascript - 从包含特定关键字的 json 数据中删除所有对象
- javascript - 如何将文本文件的内容包含到我的网站中?
- google-contacts-api - 更改 android 中的二维码色调和背景颜色
- android - 缓冲区和 glVertexAttribPointer 之间的关系
- r - 如何过滤特定日期范围内的数据集?
- yii - 如何在 yii 中使用cabinfk_id 获取机舱名称?
- sql - 从谷歌大查询中获取广告词的电话和电话印象
- windows - 从任务调度程序运行 FORMAT 命令
- angular - AngularFire - 将来自 firestore 集合查询的数据推送到数组中
- ios - 如何使用 UIBezierPath 为 Button 创建特定形状,如下面的 Swift 代码附加图像所示?