[英]Set TimeOut to React Function
我有以下對象列表:
mediaList[
{id:1, url:"www.example.com/image1", adType:"image/jpeg"},
{id:2, url:"www.example.com/image2", adType:"image/jpg"},
{id:3, url:"www.example.com/video1", adType: "video/mp4"}
]
我需要創建一個具有可配置持續時間(1秒,5秒,10秒)的幻燈片。 到目前為止,我可以從mediaList
生成媒體列表
renderSlideshow(ad){
let adType =ad.adType;
if(type.includes("image")){
return(
<div className="imagePreview">
<img src={ad.url} />
</div>
);
}else if (adType.includes("video")){
return(
<video className="videoPreview" controls>
<source src={ad.url} type={adType}/>
Your browser does not support the video tag.
</video>
)
}
}
render(){
return(
<div>
{this.props.mediaList.map(this.renderSlideshow.bind(this))}
</div>
)
}
我現在想做的是一次生成一個可配置的自動播放媒體。
我知道我需要使用某種形式的setTimeout函數,例如以下示例:
setTimeout(function(){
this.setState({submitted:false});
}.bind(this),5000); // wait 5 seconds, then reset to false
我只是不確定如何在這種情況下實現它。 (我相信我需要使用css來進行淡入淡出過渡,但是我一開始只是很困惑如何創建過渡)
如果要每5秒更換一次媒體,則必須更新狀態以重新呈現組件。您還可以使用setInterval
代替setTimeout
。 setTimeout
將僅觸發一次, setInterval
將每X毫秒觸發一次。 這里看起來可能是這樣:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { activeMediaIndex: 0 };
}
componentDidMount() {
setInterval(this.changeActiveMedia.bind(this), 5000);
}
changeActiveMedia() {
const mediaListLength = this.props.medias.length;
let nextMediaIndex = this.state.activeMediaIndex + 1;
if(nextMediaIndex >= mediaListLength) {
nextMediaIndex = 0;
}
this.setState({ activeMediaIndex:nextMediaIndex });
}
renderSlideshow(){
const ad = this.props.medias[this.state.activeMediaIndex];
let adType = ad.adType;
if(type.includes("image")){
return(
<div className="imagePreview">
<img src={ad.url} />
</div>
);
}else if (adType.includes("video")){
return(
<video className="videoPreview" controls>
<source src={ad.url} type={adType}/>
Your browser does not support the video tag.
</video>
)
}
}
render(){
return(
<div>
{this.renderSlideshow()}
</div>
)
}
}
基本上,代碼正在執行的是每5秒鍾將activeMediaIndex更改為下一個。 通過更新狀態,您將觸發重新渲染。 渲染媒體時,只需渲染一種媒體(您也可以像經典幻燈片一樣渲染前一種和后一種)。 這樣,您將每隔5秒渲染一次新媒體。
不要忘記清除超時以防止內存泄漏:
componentDidMount() {
this.timeout = setTimeout(() => {
...
}, 300);
}
componentWillUnmount() {
clearTimeout(this.timeout);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.