next-useragentnext.js 解析用户代理字符串工具

联合创作 · 2023-09-19 19:45

next-useragent 用于为 next.js 解析浏览器的用户代理字符串。


安装


$ npm install next-useragent

用法


next-useragent 的用法非常简单,使用withUserAgent方法,可以随时随地访问用户代理的详细信息。



  • 作为 getInitialProps 方法的参数传递。

  • 作为 React 组件的属性传递。


高阶组件


import React from 'react'
import dynamic from 'next/dynamic'
import { WithUserAgentProps, withUserAgent } from 'next-useragent'

const DesktopContent = dynamic(() => import('./desktop-content'))
const MobileContent = dynamic(() => import('./mobile-content'))

class IndexPage extends React.Component<WithUserAgentProps> {

static async getInitialProps(ctx) {
return { useragent: ctx.ua.source }
}

render() {
const { ua, useragent } = this.props

return (
<>
<p>{ useragent }</p>
{ ua.isMobile ? (
<MobileContent />
) : (
<DesktopContent />
) }
</>
)
}
}

export default withUserAgent(IndexPage)
浏览 19
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报