admin管理员组

文章数量:1289911

I would like to create a background consisting of 4 images that would slide from left to right each delayed by 2 seconds. I have the images stored locally. I can't figure out how can i achieve that.

Thanks for your time!

Chris.

I would like to create a background consisting of 4 images that would slide from left to right each delayed by 2 seconds. I have the images stored locally. I can't figure out how can i achieve that.

Thanks for your time!

Chris.

Share Improve this question edited Jan 22, 2021 at 17:48 benomatis 5,6437 gold badges39 silver badges60 bronze badges asked Mar 28, 2017 at 9:12 misi06misi06 2891 gold badge8 silver badges17 bronze badges 2
  • use the horizontal scroll view facebook.github.io/react-native/docs/scrollview.html – JainZz Commented Mar 28, 2017 at 9:38
  • I would background to change automatically. I cannot see such a property in a documentation of ScrollView tho. – misi06 Commented Mar 28, 2017 at 9:45
Add a ment  | 

2 Answers 2

Reset to default 7

Here is a sample logic for your question.

const { width, height } = Dimensions.get('window');
export default class CustomApp extends Component {

  ponentDidMount() {
    let scrollValue = 0;
    setInterval(function(){
      scrollValue = scrollValue + width;   // width = screen width 
      _scrollView.scrollTo({x: scrollValue}) 
    }, 3000);
  }
  render() {
    return (
     <View>
       <ScrollView 
        ref={(scrollView) => { _scrollView = scrollView; }}
        horizontal={true} pagingEnabled={true} 
        >
          <Image source={require('./1.jpg')} style={{height, width}} />
          <Image source={require('./2.jpg')} style={{height, width}} />
          <Image source={require('./1.jpg')} style={{height, width}} />
          <Image source={require('./2.jpg')} style={{height, width}} />
       </ScrollView>
       <View style={{ position: 'absolute'}}>
         <Text>Page Content</Text>
      </View>
     </View>
    );
  }
}

Complementing JainZz's answer, here is my approach to make images slides infinitely

ponentDidMount() {
    const numOfBackground = 4;
    let scrollValue = 0, scrolled = 0;
    setInterval(function () {
        scrolled++;
        if(scrolled < numOfBackground)
            scrollValue = scrollValue + width;
        else{
            scrollValue = 0;
            scrolled = 0
        }
        _scrollView.scrollTo({ x: scrollValue, animated: false })
    }, 3000);
}

I added a logic to check if it's the last image, and scroll it back to the first image. I also change scrollTo prop animated to false to make it look smoother

本文标签: javascriptSliding background images in React NativeStack Overflow