h5响应式集团网站推荐百度销售系统登录
写在前面
最近在项目中遇到了一个这样的需求:给一个模块做埋点,要求埋点的触发时机是当模块露出50%且停留300毫秒才进行上报
开搞
首先要有一个View
<View></View>
然后在View
里定义一个ref
<View ref = { viewRef }></View>
然后写一个定时器,每隔300毫秒触发一次
setinterval(() => {// do something
}, 300)
然后判断viewRef
是否露出50%,如果露出50%则触发埋点
import {Dimensions} from "react-native";this.state = {// 是否可埋点isExpoesd: false,// 是否停留300毫秒isStayThreeHundredMilliseconds: false,}
setinterval(() => {if(this.viewRef.current){this.viewRef.current.measure((x, y, width, height, pageX, pageY) => {// 获取屏幕高度let windowHeight = Dimensions.get('window').height;// 模块露出50%坐标值let moduleTop = windowHeight - (height / 2);// // 商品露出的高度// let exposeHeight = windowHeight - pageY;// // 卡片露出的高度// let cardPosHeight = windowHeight - pageY;// // 卡片露出的比例// let proportion = cardPosHeight / height;// if(exposeHeight > height){// exposeHeight = '100%'// }// if(exposeHeight < 0){// exposeHeight = `商品距离显示还有${Math.abs(exposeHeight)}`;// proportion = '卡片还没露出呢!'// }// if(proportion > 1){// proportion = '100%'// }// let tip = `// 这个商品露出了${moduleTop > pageY ? '大于50' : '小于50'},// 具体参数如下↓↓↓↓↓// 商品名称:${name},// 商品ID:${Id}// 屏幕高度:${windowHeight},// 模块整体高度:${height},// 模块最高点坐标:${pageY},// 如果模块坐标低于${moduleTop},说明露出大于50%,// 商品露出了:${exposeHeight}// 卡片露出的比例是:${proportion}// `// console.log('------------------------分界线开始---------------------------------')// console.log(tip)this.setState(prevState => {let newIsExpoesd = moduleTop > pageY ? true : false;// 比较当前状态与新状态if (newIsExpoesd !== prevState.isExpoesd) {this.setState({isExpoesd: newIsExpoesd }); // 返回新的状态}// console.log(`Toggled state changed from ${prevState.isExpoesd} to ${newIsExpoesd}`);if((prevState.isExpoesd === newIsExpoesd) && (prevState.isExpoesd === true)){// console.log('可以埋点')this.state.isStayThreeHundredMilliseconds = true;return true} else {// console.log('不可以埋点')this.state.isStayThreeHundredMilliseconds = false;return false}});// console.log('------------------------分界线结束---------------------------------')});}
}, 300)