我试图从App.js文件中两次调用Component,但是在渲染时我得到了该组件的相同实例。该组件将从Unsplash获取随机图像。现在,我想出了一些解决方案,例如先清除实例,然后再次调用组件。我们如何通过再次调用同一组件来创建该组件的新实例?
代码: //Parallex.js
import React from 'react';
import $ from 'jquery';
import { Button } from 'reactstrap';
import './components/style/style.css';
class Parallex extends React.Component {
constructor() {
super();
this.para = this.para.bind(this);
}
componentDidMount = () => {
this.para();
document.addEventListener('scroll', this.isInViewport, true);
}
para() {
$(document).ready(function(){
var scrolled = $(window).scrollTop()
console.log("--------->" + scrolled);
$('.parallax').each(function(index) {
var imageSrc = $(this).data('image-src')
var imageHeight = $(this).data('height')
$(this).css('background-image','url(' + imageSrc + ')')
$(this).css('height', imageHeight)
var initY = $(this).offset().top
var height = $(this).height()
var diff = scrolled - initY
var ratio = Math.round((diff / height) * 100)
$(this).css('background-position','center ' + parseInt(-(ratio * 1.5)) + 'px')
})
$(window).scroll(function() {
var scrolled = $(window).scrollTop()
$('.parallax').each(function(index, element) {
var initY = $(this).offset().top
var height = $(this).height()
var diff = scrolled - initY
var ratio = Math.round((diff / height) * 100)
$(this).css('background-position','center ' + parseInt(-(ratio * 1.5)) + 'px')
})
})
})
}
render() {
return (
<div ref='UniqueElementIdentifies' className="parallax" id="parallax-2" data-image-src="**https://source.unsplash.com/random/1920x1081"** data-height="400px">
<div className="caption">
<Button>Know more</Button>
</div>
</div>
)
}
}
export default Parallex;
App.js:
import React, { Component } from 'react';
import NavbarComponent from './components/js/Navbar';
import Example from './carousal';
import Parallex from './parallex';
import FooteraboutUs from './footer-aboutus';
import {
Jumbotron,
Button,
} from 'reactstrap';
import './App.css';
import './Sticky-Navbar.css';
class App extends Component {
render() {
return (
<div>
<div>
<Parallex/>
</div>
<div>
<Example/>
</div>
<div>
<Parallex/>
</div>
<div>
<FooteraboutUs/>
</div>
</div>
);
}
}
export default App;
答案 0 :(得分:0)