设置 TimeOut 以响应函数

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 而不是 setTimeoutsetTimeout 只会触发一次,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);
  }