我有一个包含图像的数据列表。我想制作图像轮播。为此,我创建了卡组件,我想在此一次显示4张卡,其余应隐藏。然后我要在setTimeout
中的5s
中显示剩余的内容,但一次只能显示一次。
到目前为止,我已经做到了。
about.js
import './about.scss';
import data from '../../data/data';
import CardSection from './card';
class About extends React.Component{
constructor(props){
super(props);
this.state = {
properties: data.properties,
property: data.properties[0]
}
}
nextProperty = () => {
const newIndex = this.state.property.index+4;
this.setState({
property: data.properties[newIndex]
})
}
prevProperty = () => {
const newIndex = this.state.property.index-4;
this.setState({
property: data.properties[newIndex]
})
}
render() {
const {property, properties} = this.state;
return (
<div className="section about__wrapper">
<div>
<button
onClick={() => this.nextProperty()}
disabled={property.index === data.properties.length-1}
>Next</button>
<button
onClick={() => this.prevProperty()}
disabled={property.index === 0}
>Prev</button>
<Container className="card__container">
<div class="card__main" style={{
'transform': `translateX(-${property.index*(100/properties.length)}%)`
}}>
{
this.state.properties.map(property => (
<CardSection property={property}/>
))
}
</div>
</Container>
</div>
</div>
)
}
}
export default About
about.scss
.card__container{
overflow-x: hidden;
}
.card__main{
display: flex;
position: absolute;
transition: transform 300ms cubic-bezier(0.455, 0.03, 0.515, 0.955);
.card__wrapper {
padding: 20px;
flex: 1;
min-width: 300px;
}
}
card.js
import React from "react";
import { Card, CardImg, CardText, CardBody,
CardTitle, CardSubtitle, Button } from 'reactstrap';
class CardSection extends React.Component {
render() {
return (
<div className="card__wrapper">
<Card>
<CardImg top width="100%" src={this.props.property.picture} alt="Card image cap" />
<CardBody>
<CardTitle>{this.props.property.city}</CardTitle>
<CardSubtitle>{this.props.property.address}</CardSubtitle>
<CardText>Some quick example text to build on the card title and make up the bulk of the card's content.</CardText>
<Button>Button</Button>
</CardBody>
</Card>
</div>
);
}
}
export default CardSection;
我在其中添加了转换功能,以更改卡片的onclick,但我希望它们自动更改并隐藏剩余的卡片。
现在看起来像这样,
答案 0 :(得分:1)
您可以使用setInterval在componentDidMount方法中添加项目
componentDidMount() {
this.interval = setInterval(() => this.setState({
properties:data.properties /* add your data*/ }), 4000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
答案 1 :(得分:0)
您可以拥有一个名为.randomElement()
的属性,该属性包含需要显示的卡片ID的数组,并使用该属性在卡片的div上设置一个名为.random()
的布尔属性。
您还可以执行以下示例中所示的操作,该示例还使用showCardIds
作为状态。它仅针对需要呈现的hidden
进行过滤,并过滤其余部分。
这是一个示例:
showCardIds
这样,只有出现在property
数组中的那些元素才会出现,需要编写更多的逻辑来填充...
{
this.state.properties.filter((property, index) => showCardIds.includes(index)).map(property => (
<CardSection property={property}/>
))
}
...
的id
希望这会有所帮助。 HTML5支持showCardIds
属性,除非真正“古老”,否则它应可在大多数浏览器上使用。