我有下面的代码,其中我有一个组件,它是幻灯片的旋转木马(来自nuka- carousel库)。我希望当屏幕宽度低于某个级别(729px)时,属性slideWidth={0.5}为slideWidth={1},这样当屏幕变小时,您只能看到一张幻灯片,而不是一次看到多张幻灯片。
我尝试过使用媒体查询,但我找不到一种方法来根据样式设置属性。
import React from 'react'
import Carousel from 'nuka-carousel'
class Quotes extends React.Component {
state = {
slideIndex: 0,
};
render() {
return (
<Carousel slideWidth={0.5}>
{this.props.slides.map(slide => (
<Slide>
.... Content ....
</Slide>
))}
</Carousel>
)
}
};以前有没有人遇到过这个问题,或者能想出解决方案?
谢谢!
发布于 2019-08-21 00:03:57
您可以使用类似于JS的媒体查询的matchMedia API -您可以使用断点设置一个,并更改JS变量,这将允许您,比如说,有条件地呈现您想要的旋转木马:
var mediaQueryList = window.matchMedia('(min-width: 729px)');
return (
{ mediaQueryList.matches && //matches
<Carousel slideWidth={0.5}>
{this.props.slides.map(slide => (
<Slide>
.... Content ....
</Slide>
))}
</Carousel>
}
{ !mediaQueryList.matches && //doesn't match
<Carousel slideWidth={1}>
{this.props.slides.map(slide => (
<Slide>
.... Content ....
</Slide>
))}
</Carousel>
}
)所以这里的想法是,当MQ匹配时,我们呈现0.5转盘,当它不匹配时,我们呈现1转盘。如果需要,您还可以设置回调并控制变量的值:
function handleWidthChange(evt) {
if (evt.matches) {
/* The viewport is currently wide */
myVariable = 0.5;
} else {
/* The viewport is currently narrow */
myVariable = 1;
}
}
mediaQueryList.addListener(handleWidthChange); // Add the callback function as a listener to the query list.
handleWidthChange(mediaQueryList);//call it
return (
<Carousel slideWidth={ myVariable }>
{this.props.slides.map(slide => (
<Slide>
.... Content ....
</Slide>
))}
</Carousel>
)https://stackoverflow.com/questions/57576293
复制相似问题