我有以下对象列表:

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秒渲染一次新媒体。

关于javascript - 将超时设置为React函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42934781/

10-14 03:11