Set TimeOut to React Function

los*_*193 2 javascript timeout slideshow reactjs

I have the following object list:

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"}
]
Run Code Online (Sandbox Code Playgroud)

我需要创建一个具有可配置持续时间(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>
    )
 }
Run Code Online (Sandbox Code Playgroud)

我现在想要做的是一次生成一个媒体,并具有可配置的自动播放持续时间。

我知道我需要使用某种形式的 setTimeout 函数,如下例所示:

setTimeout(function(){
         this.setState({submitted:false});
    }.bind(this),5000);  // wait 5 seconds, then reset to false
Run Code Online (Sandbox Code Playgroud)

我只是不确定如何在这种情况下实现它。(我相信我需要使用 css 来实现淡入淡出过渡,但我一开始就对如何创建过渡感到困惑)

Vin*_*our 5

如果您想每 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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

基本上代码所做的是每 5 秒,将 activeMediaIndex 更改为下一个。通过更新状态,您将触发重新渲染。渲染媒体时,只渲染一个媒体(您也可以像经典幻灯片一样渲染上一个和下一个)。这样,每 5 秒,您将渲染一个新媒体。


Leo*_*rdo 5

不要忘记清除超时以防止内存泄漏:

  componentDidMount() {
    this.timeout = setTimeout(() => {
     ...
    }, 300);
  }

  componentWillUnmount() {
    clearTimeout(this.timeout);
  }
Run Code Online (Sandbox Code Playgroud)