将css视差图像材料化,然后导航到另一条路线然后返回

问题描述 投票:0回答:1

我已经按照以下代码使用了物化CSS来对3张图像产生视差效果。当网页在开发服务器中加载时,所有页面都运行良好,但是,如果我离开页面导航到另一个组件,然后再次返回,则所有视差图像都会消失,好像视差库不再工作一样。如果我重新加载网页,它们都会再次正常显示。

import React, { Component } from 'react'
import code from '../images/code.jpg';
import coffee from '../images/coffee.jpg';
import mac from '../images/mac.jpg';
import M from 'materialize-css/dist/js/materialize.min.js';

export default class About extends Component {

componentDidMount() {

    document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.parallax');
    var instances = M.Parallax.init(elems, {});
 });
}


 render() {

     return (

             <div>


                <div className="parallax-container">
                    <div className="parallax"> <img className="responsive-img" src={coffee}
                </div>  

                <div className="parallax-container">
                    <div className="parallax"> <img className="responsive-img" src={coffee}
                </div>   

               <div className="parallax-container">
                    <div className="parallax"> <img className="responsive-img" src={coffee}
                </div>    

          </div>


      )
 }
javascript hook materialize parallax
1个回答
1
投票

您不需要addEventListener中的componentDidMount。不需要它,因为componentDidMount生命周期方法为您提供了初始化组件中要使用的任何库(视差情况)所需的功能。在路由之间切换时,视差图像消失的原因可能是因为在路由之间切换时DOMContentLoaded不再触发,因此视差库未初始化。

[请查看React的生命周期图,以更好地了解这些生命周期方法如何工作:http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

© www.soinside.com 2019 - 2024. All rights reserved.