gpt4 book ai didi

reactjs - React 多轮播不进行服务器端渲染

转载 作者:行者123 更新时间:2023-12-03 20:39:47 26 4
gpt4 key购买 nike

这是我的 Carousel,我正在使用 react-multi-carousel 和 Nextjs,我正在激活 ssr 选项

import Carousel from 'react-multi-carousel'
import 'react-multi-carousel/lib/styles.css'

import CarouselImage from './CarouselImage'

const responsive = {
desktop: {
breakpoint: { max: 4000, min: 1024 },
items: 1,
paritialVisibilityGutter: 60,
},
tablet: {
breakpoint: { max: 1024, min: 464 },
items: 1,
paritialVisibilityGutter: 50,
},
mobile: {
breakpoint: { max: 464, min: 0 },
items: 1,
paritialVisibilityGutter: 30,
},
}

const imageFolders = [
'/images/carousel/post-1',
'/images/carousel/post-2',
]

export default function CarouselComponent() {
return (
<div>
<div>
<div>
<Carousel
ssr
infinite={true}
autoPlay={true}
containerClass='carousel-container'
itemClass='carousel-image-item'
autoPlaySpeed={6000}
responsive={responsive}
>
{imageFolders.map((imageFolder) => (
<CarouselImage
imageFolder={imageFolder} />
))}
</Carousel>
</div>
</div>
</div>
)
}
这是 CarouselImage,在 img 标签下方我有文本 hola
export default function CarouselImage({ imageFolder }) {
return (
<div>
<img
key={imageFolder}
srcSet={`${imageFolder}/1270-520.png, ${imageFolder}/770-520.png 2x`}
src={`${imageFolder}/770-520.png`}
/>
<p>hola</p>
</div>
)
}
当我单击查看页面源代码时,我看不到文本“hola”。
我究竟做错了什么?我是否需要添加一些其他配置来进行服务器端渲染?我已经尝试过开发模式,我也做过构建

最佳答案

使用 ssr本身是不够的,deviceType还需要为服务器端渲染设置 Prop 。

<Carousel
ssr
deviceType={deviceType} // `deviceType` needs to be set
infinite={true}
autoPlay={true}
containerClass='carousel-container'
itemClass='carousel-image-item'
autoPlaySpeed={6000}
responsive={responsive}
>
{imageFolders.map((imageFolder) => (
<CarouselImage imageFolder={imageFolder} />
))}
</Carousel>

您如何定义 deviceType由您决定,但 official SSR example for react-multi-carousel 通过解析 User-Agent 提供了一个可能的解决方案.
import UAParser from 'ua-parser-js'

// ...

Index.getInitialProps = ({ req }) => {
let userAgent

if (req) {
userAgent = req.headers['user-agent']
} else {
userAgent = navigator.userAgent
}

const parser = new UAParser()
parser.setUA(userAgent)
const result = parser.getResult()
const deviceType = (result.device && result.device.type) || 'desktop'

return { deviceType }
};

关于reactjs - React 多轮播不进行服务器端渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67627482/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com