next-useragentnext.js 解析用户代理字符串工具
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)
评论
