我正在尝试做什么: 加载组件后,我想从getMainBg.js调用getbg()来更改背景。
我的主页组件 -
var url = []; //will store image urls
function getbg(){
var random = Math.floor(Math.random() * (url.length + 1)) + 0;
document.getElementsByTagName("body")[0].style = "background-
image: url('"+url[random]+"');";
console.log('background loaded');
}
我的getMainBg.js -
{{1}}
我尝试过,但没有工作。
答案 0 :(得分:1)
您可以使用React组件的componentDidMount
函数,该函数在安装React组件时执行一次。您还需要在导入和调用之前导出该函数
import React, { Component } from 'react';
import { getbg } from './Scripts/getMainBg.js';
class Homepage extends Component {
componentDidMount() {
getbg();
}
render() {
return (
<homepage>
<div className="recent">
<h1>Recently Added/Updated</h1>
<div className="image">IMAGE1</div>
</div>
<div className="popular">
<h1>Popular Right Now</h1>
<div className="image"></div>
</div>
<div className="picks">
<h1>Our Picks</h1>
<div className="image"></div>
<div className="image"></div>
</div>
</homepage>
);
}
}
<强> getMainBg.js 强>
var url = []; //will store image urls
export function getbg(){
var random = Math.floor(Math.random() * (url.length + 1)) + 0;
document.getElementsByTagName("body")[0].style = "background-
image: url('"+url[random]+"');";
console.log('background loaded');
}