2017-03-21 2 views
1

를 반응 나는 다음과 같은 개체 목록이 있습니다설정 시간 초과 기능

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를 사용할 필요가 있다고 생각하지만, 처음에는 전환을 만드는 방법을 모르겠다.)

답변

3

매 5 초마다 미디어를 변경하려는 경우, 구성 요소를 다시 렌더링하기 위해 상태를 업데이트하려면 setTimeout 대신 setInterval을 사용할 수도 있습니다. setTimeout이 한 번만 트리거되고, X 밀리 초마다 setInterval이 트리거됩니다. 여기처럼 보일 수 있습니다 무엇 :

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 초마다 새로운 미디어를 렌더링합니다.

+0

이것은 약간의 작은 업데이 트로 그것을 밖으로 테스트하고 그것은 작동합니다! 감사합니다 – lost9123193

+0

아주 좋은 접근! 그것은 나를 도왔다! 고마워. – Aayushi