gpt4 book ai didi

javascript - 加载 React 组件后,如何调用 javascript 文件中存在的函数?

转载 作者:行者123 更新时间:2023-12-03 02:29:10 25 4
gpt4 key购买 nike

我正在尝试做的事情:加载组件后,我想从 getMainBg.js 调用 getbg() 来更改背景。

我的主页组件 -

import React, { Component } from 'react';
import './Scripts/getMainBg.js';
class Homepage extends Component {
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>
);
}
}

export default Homepage;

我的 getMainBg.js -

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');
}

我尝试过,但没有成功。

最佳答案

您可以使用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');
}

关于javascript - 加载 React 组件后,如何调用 javascript 文件中存在的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48808573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com