更改时背景图像闪烁 - 反应

Background Image flickering when change - react

我一直在重写我的网站 ondeband.com - 它目前是一个 wordpress 网站,我用 React 编写它大约一个月了。

我不打算对主页进行过多更改 - 它的背景图片每隔几秒钟就会更改一次。你可以在我上面的 link 中看到它。

问题是...在我的网站的新 React 版本上 - 它在每次图像更改之间闪烁 - 特别是当我将它推送到 heroku 时。它 99% 的时间都在我的本地开发服务器上工作。

我感觉是因为图片 'preloading' 的缘故?也许你能给我指出正确的方向——这是我的应用程序主页的代码。

className 为 'homePage' 的 div 是 bg 图像加载到内联样式中的位置。变量 bgImage 存储在状态中。我使用 useEffect 挂钩启动函数 'bgTransition',随机更改每个图像。

    import React, { useState, useEffect } from "react";
import NavBarA from "./components/NavBarA";
import { Router, Route, Switch } from "react-router-dom";
import BookABand2 from "./components/Profile/BookABand2";
import LiveProfile from './components/BookABand/LiveProfile'
import Account from './components/Account/Account'
import history from "./uitls/history";
import PrivateRoute from "./components/PrivateRoute";
import 'bootstrap/dist/css/bootstrap.min.css';
import AqgSetup3 from "./components/AqgSetup3";
import './App.css';
import { useAuth0 } from './react-auth0-spa'
import Banjo from './BackgroundImgs/Banjo.jpg'
import Hands from './BackgroundImgs/Hands.jpg'
import Mic from './BackgroundImgs/Mic.jpg'
import Sax from './BackgroundImgs/Sax.jpg'
import { Button } from 'reactstrap'

function App() {
  const { user } = useAuth0()
  const [bgImgArray] = useState([Banjo, Hands, Mic, Sax])
  const [ bgImg, setBgImg ] = useState(Banjo)
  const { loginWithRedirect, isAuthenticated } = useAuth0();

  useEffect(() => {
    bgTransition()
  }, [] )

  const bgTransition = () => {
    let newNum = Math.floor(Math.random() * 4)
    setBgImg(bgImgArray[newNum])
    setTimeout(() => {
      bgTransition()
    }, 5000)
  }

  if(!bgImgArray){
    return <div>loading...</div>
  }

  return (
    <div className="App h-100" style={{
      paddingTop: user ? '85px' : '0px'
    }}>
      <Router history={history}>
        <header>
          <NavBarA color={ user ? 'light' : ''} className={user ? 'navbar text-dark fixed-top shadow-lg' : "navbar text-light fixed-top"}/>
        </header>
        <Switch>
          <Route path="/" exact >
            <div className='homePage h-100' style={{
              display: !isAuthenticated ? 'block' : 'none',
              backgroundImage: `url(${bgImg})`,
              backgroundRepeat: 'no-repeat',
              backgroundSize: 'cover',
              webkitTransition: 'background-image 1s ease-in-out',
              transition: 'background-image 1s ease-in-out',
            }}>
              <div className='h-100 w-100 position-absolute'style={{
                background: 'linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) )',
                zIndex: '10'
              }}/>
              <div className="d-flex flex-column w-100 h-100 align-items-center justify-content-center position-relative" style={{zIndex: '100'}}>
              <h1 className='text-light'>On Demand</h1>
                <h1 className='text-light'>On DeBand</h1>
                <h6 className='text-light'>Find, Support, and Book Local Bands</h6>
                <div className='d-flex flex-row'>
                  <Button outline color='light' size='lg' className='mx-2 my-2' onClick={() => {loginWithRedirect()}}>Find Bands</Button>
                </div>
              </div>
              <div>

              </div>

            </div>

            <div style={{
              display: user ? 'block' : 'none',
            }}>
              <BookABand2 />
            </div>
          </Route>
          <PrivateRoute path="/BookABand2" component={BookABand2} />
          <PrivateRoute path="/AqgSetup3/:id" component={AqgSetup3} />
          <PrivateRoute path="/band/:id" component={LiveProfile} />
          <PrivateRoute path="/account" component={Account} />
        </Switch>
      </Router>
    </div>
  );
}

export default App;

感谢您的帮助!

您只需 html 即可完成,只需对您的 React 代码进行一些小的调整。

想早点下载图片可以关注。唯一的问题是,您不知道图像的 url,因为一旦您构建网站,它就会随机化。

为缓解这种情况,请将图像从 src 文件夹移至 public 文件夹。我假设您会使用 /public/images/ 来存储它们。这是修改后的代码:

index.html

<head>
..
..
<link rel="preload" href="%PUBLIC_URL%/images/Banjo.jpg" as="image">
<link rel="preload" href="%PUBLIC_URL%/images/Hands.jpg" as="image">
<link rel="preload" href="%PUBLIC_URL%/images/Mic.jpg" as="image">
<link rel="preload" href="%PUBLIC_URL%/images/Sax.jpg" as="image">
...
</head>

App.js

import React, { useState, useEffect } from "react";
import NavBarA from "./components/NavBarA";
import { Router, Route, Switch } from "react-router-dom";
import BookABand2 from "./components/Profile/BookABand2";
import LiveProfile from './components/BookABand/LiveProfile'
import Account from './components/Account/Account'
import history from "./uitls/history";
import PrivateRoute from "./components/PrivateRoute";
import 'bootstrap/dist/css/bootstrap.min.css';
import AqgSetup3 from "./components/AqgSetup3";
import './App.css';
import { useAuth0 } from './react-auth0-spa'
import { Button } from 'reactstrap'

function App() {
  const [bgImgArray] = useState(['Banjo.jpg', 'Hands.jpg', 'Mic.jpg', 'Sax.jpg'])
  ...
  return (
    <div className="App h-100" style={{
      paddingTop: user ? '85px' : '0px'
    }}>
      <Router history={history}>
        ...
        <Switch>
          <Route path="/" exact >
            <div className='homePage h-100' style={{
              display: !isAuthenticated ? 'block' : 'none',
              backgroundImage: `url(/public/images/${bgImg})`,
              backgroundRepeat: 'no-repeat',
              backgroundSize: 'cover',
              webkitTransition: 'background-image 1s ease-in-out',
              transition: 'background-image 1s ease-in-out',
            }}>
              ...
            </div>
          </Route>
          ...
        </Switch>
      </Router>
    </div>
  );
}

export default App;