我有一个非常简单的HOC,其代码是
import React from 'react';
const withRandomImage = Comp => props => {
const x = Math.floor(Math.random() * 26);
return <Comp {...props} image={x} />
}
export default withRandomImage;
它与代码为的ImageBar组件一起使用
import React from 'react';
import styled from 'styled-components';
import withRandomImage from '../../hocs/WithRandomImage';
const Bar = styled.div`
display: block;
height: 310px;
background-image: url(${props => props.image});
background-size: cover;
background-position: 0px -400px;
background-repeat: no-repeat;
`
const formatWrapper = {
width: "100%",
height: "310px"
}
class ImageBar extends React.Component {
getBgImage = () => {
console.log(window.location.origin);
return window.location.origin + '/hp/' + this.props.image + '.jpg';
}
render() {
console.log("Image: ",this.getBgImage());
return (
<Bar className="ImageBar" image={this.getBgImage()}>
<div className="container-fluid">
<div className="row align-items-center" style={formatWrapper}>
{this.props.inner}
</div>
</div>
</Bar>
)
}
}
export default withRandomImage(ImageBar);
想法是每次刷新页面时,将随机图像用作背景图像。图像从React的/hp/
目录中的public
文件夹中提供。
首次渲染组件时,一切正常。但是在ImageBar
内部,我有一些组件(在this.props.inner
中传递),并附加了事件侦听器。每次触发事件ID的背景图片都会消失。
这是呈现此ImageBar
的组件的示例。
render() {
return (
<div>
<Header />
<ImageBar inner={this.getSearchBar()} />
</div>
)
}
我认为这与组件的生命周期有关,但是无法确切地了解正在发生的事情。
有什么建议吗?
我认为math.random() * 26
正在生成一个hp
文件夹中没有正确图像的网址。你检查了吗?
请记住,每个渲染器都会生成一个新的随机值和一个新的道具。您可以通过将数字的生成移出增强组件之外来将其“冻结”为“第一个”生成的值。
类似的东西
const withRandomImage = Comp => {
const x = Math.floor(Math.random() * 26);
// when rereder occurs, only the code below will be run - so the image is always the same
return props => <Comp {...props} image={x} />
}