在react的特定视口中更改JSON数据源



我正在使用react进行一个项目,我将JSON文件中的数据插入到reducer函数中以管理内容状态。然而,在某个视口,提供了另一个需要显示的图像,而不是另一个图像。如果我使用useReducer,我怎么能改变图像源一旦达到某个视口?附件是我的代码片段

JSON数据源示例:

{
"name": "Starry Night",
"year": 1889,
"description": "Although The Starry Night was painted during the day in Van Gogh's ground-floor studio, it would be inaccurate to state that the picture was painted from memory. The view has been identified as the one from his bedroom window, facing east, a view which Van Gogh painted variations of no fewer than twenty-one times, including The Starry Night. "Through the iron-barred window," he wrote to his brother, Theo, around 23 May 1889, "I can see an enclosed square of wheat ... above which, in the morning, I watch the sun rise in all its glory."",
"source": "https://en.wikipedia.org/wiki/The_Starry_Night",
"artist": {
"image": "../assets/starry-night/artist.jpg",
"name": "Vincent Van Gogh"
},
"images": {
"thumbnail": "../assets/starry-night/thumbnail.jpg",
"hero": {
"small": "../assets/starry-night/hero-small.jpg", //This is mobile
"large": "../assets/starry-night/hero-large.jpg"  //This is for tablet and up
},
"gallery": "../assets/starry-night/gallery.jpg"
}
},

//其中使用useState():

渲染图像
<ImageWorks
className="gallery__image"
source={state.image}
alt={`"${state.name}" by ${state.artist}, ${state.year}`}
/>

//如何使用useReducer()管理状态:

const [i, setIndex] = useState(0)
const contentReducer = (state, actions) => {
switch (actions.type) {
case ACTIONS.UPDATE:
return {
...state,
image: data[i].images.hero.small,
name: data[i].name,
artist: data[i].artist.name,
artistImg: data[i].artist.image,
year: data[i].year,
description: data[i].description,
source: data[i].source,
}
default:
return state
}
}
const [state, dispatch] = useReducer(contentReducer, {
image: data[0].images.hero.small,
name: data[0].name,
artist: data[0].artist.name,
artistImg: data[0].artist.image,
year: data[0].year,
description: data[0].description,
source: data[0].source,
})

例如,我需要从'data[0].images.hero更改图像。小的' to 'data[0].images.hero。

谢谢你的帮助!

解决了我自己的问题

使用这个媒体查询包可以轻松实现: https://www.npmjs.com/package/react-responsive

阅读关于如何实现的文档,在我的情况下,我将如何使用它:

const isMobile = useMediaQuery({ query: '(max-width: 375px)' })
const [state, dispatch] = useReducer(contentReducer, {
imageMobile: data[0].images.hero.small, // set below 375px
imageLarge: data[0].images.hero.large, // set above 375px
name: data[0].name,
artist: data[0].artist.name,
artistImg: data[0].artist.image,
year: data[0].year,
description: data[0].description,
source: data[0].source,
})
<ImageWorks
className="gallery__image"
source={isMobile ? state.imageMobile : state.imageLarge} // ternary
alt={`"${state.name}" by ${state.artist}, ${state.year}`}
/>

最新更新