[英]How to detect device is mobile when the website is clicked through TikTok?
注意:出于某种原因,我的代码适用于通过 Instagram 而不是通过 TikTok 单击网站链接的情况。
我正在尝试检测设备是否为移动设备,以便以不同方式呈现屏幕。 我们在桌面上有一个 4 列的网格布局,如果设备是移动设备,我们只想显示 1 或 2 列。
我们声明 const [columns, setColumns] = React.useState(4);
这是检测屏幕尺寸的现有代码:
window.addEventListener(
"resize",
function (event) {
if (event.target.innerWidth > 700) {
setColumns(4);
} else if (
event.target.innerWidth < 700 &&
event.target.innerWidth > 600
) {
setColumns(3);
} else if (
event.target.innerWidth < 600 &&
event.target.innerWidth > 400
) {
setColumns(2);
} else {
setColumns(1);
}
},
true
);
对于渲染的组件,我们将这些道具从 react-grid-dnd 传递给 GridDropZone:
<GridDropZone
disableDrag={true}
id="items"
boxesPerRow={columns}
rowHeight={353}
style={{ height: `${(items.length / 4) * 350}px` }}
>
当我在 iPhone 上通过我的 Chrome 浏览器时,这个逻辑似乎足以只显示 2 列。 但是,当我尝试通过 TikTok 个人资料点击我们网站的链接时,我们似乎仍然显示 4 列。 这在 Instagram 上似乎不是问题。 为什么这与打开 Instagram 和通过我的移动 Chrome 浏览器打开它不同,您建议如何解决这个问题? 谢谢!
编辑:此修复程序仍然只适用于 iOS chrome,而不是当我通过 TikTok 打开网站时。
if (window.matchMedia("only screen and (max-width: 760px)").matches) {
setColumns(1);
}
编辑:makeStyles()
const useStyles = makeStyles((theme) => ({
root: {
backgroundColor: "#fcfcfc",
},
icon: {
marginRight: theme.spacing(2),
},
heroContent: {
backgroundColor: theme.palette.background.paper,
padding: theme.spacing(8, 0, 6),
},
heroButtons: {
marginTop: theme.spacing(4),
},
cardGrid: {
paddingTop: theme.spacing(8),
paddingBottom: theme.spacing(8),
marginTop: 10,
},
card: {
height: "100%",
display: "flex",
flexDirection: "column",
},
cardMedia: {
paddingTop: "56.25%", // 16:9
},
cardContent: {
flexGrow: 1,
},
footer: {
backgroundColor: theme.palette.background.paper,
padding: theme.spacing(6),
},
sectionDesktop: {
display: "none",
[theme.breakpoints.up("lg")]: {
display: "flex",
},
},
formControl: {
margin: theme.spacing(1),
minWidth: 150,
maxHeight: 40,
color: "black",
},
selectEmpty: {
marginTop: theme.spacing(2),
},
问题解决了。 如您所见,我有一个window.addEventListener("resize", ...)
并且它确实可以为 Instagram 制作我的网格 1 列。 但是,这对 TikTok 不起作用,因为当我通过该应用程序单击我的网站时,TikTok 似乎不会触发“调整大小”事件。
因此,我创建了一个单独的 resize() function 并在首次通过 useEffect() 呈现页面时手动调整 window 的大小。 我还添加了一个新的 if 语句,它使用window.matchMedia()
来检查设备是否是移动设备。 解决方案的代码如下所示。
function resize(innerWidth) {
if (window.matchMedia("only screen and (max-width: 760px)").matches) {
setColumns(1);
} else if (innerWidth > 700) {
setColumns(4);
} else if (
innerWidth < 700 &&
innerWidth > 600
) {
setColumns(3);
} else if (
innerWidth < 600 &&
innerWidth > 400
) {
setColumns(2);
} else {
setColumns(1);
}
}
window.addEventListener(
"resize",
function (event) {
resize(event.target.innerWidth)
},
true
);
useEffect(() => { resize(window.innerWidth) }, [])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.