简体   繁体   English

幻灯片背景图片ReactJS | 的CSS

[英]Slide background image ReactJS | CSS

I have a horizontal image that I want to use as a background. 我有一个要用作背景的水平图像。 I want to change the position of the image depending on the argument passed to the function. 我想根据传递给函数的参数来更改图像的位置。 My image: 我的形象:

在此处输入图片说明

My code so far: 到目前为止,我的代码:

import React, { Component } from 'react'

import Background from '../images/background_image.jpg';

class MoveImage extends Component{

    constructor(props) {
    super(props);
    this.state = {
      counter: 1
     }
  }

    const bgSlide = {
        backgroundImage: `url(${Background})`
    };

    moveBGImage=(id)=>{
        //slide the image depending on the id
        //so if id=2, the image should slide from screen1 to screen2
    }

    render(){
        return(
            <div style = { bgSlide } >

                <button
                    onClick = this.moveBGImage(this.state.counter+1)
                >
                    Click Me

                </button>

            </div>

            )
    }


}


export default MoveImage;

So if the counter is 2, I want to show screen2 part of the image. 因此,如果计数器为2,我想显示图像的screen2部分。 And screen1 should slide left and screen2 slide in from right. 屏幕1应该向左滑动,屏幕2应该从右滑动。 Can this be done in React? 可以在React中完成吗?

It's possible with CSS background-position : CSS background-position有可能:

 const App = () => { const [screen, setScreen] = React.useState(1) const toggleScreen = () => setScreen(s => s > 3 ? 1 : s + 1) return ( <div className={`screen nr${screen}`} onClick={toggleScreen} /> ) } ReactDOM.render(<App /> , document.getElementById('root')) 
 .screen { background: url('https://i.stack.imgur.com/72bFV.png') no-repeat 0 0; background-size: cover; width: 120px; height: 100px; transition: 300ms; } .screen.nr2 { background-position: 33.33% 0; } .screen.nr3 { background-position: 66.67% 0; } .screen.nr4 { background-position: 100% 0; } 
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script> 

Note: I used the image from question, which does not have exact 1/4 parts, so the red lines do not align exactly. 注意:我使用了问题中的图像,该图像没有精确的1/4部分,因此红线未完全对齐。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM