我有一个问题:这是我的Heroes组件
const Hero = styled.div`
display: flex;
flex-direction: column;
justify-content: flex-end;
background: linear-gradient(to top, #1f1f21 1%, #1f1f21 1%,rgba(25, 26, 27, 0) 100%) , url(${props => props.bgdesktop}) no-repeat top center;
height: 100vh;
background-size: cover;
@media (max-width:1024px) {
background: linear-gradient(to top, #1f1f21 1%, #1f1f21 1%,rgba(25, 26,
27, 0) 100%) , url(${props => props.bgtablet}) no-repeat center top;
}
@media (max-width:480px) {
background:linear-gradient(to top, rgba(31, 31, 33, 1) 2%, rgba(31, 31,33, 1) 5%,rgba(25, 26, 27, 0) 100%) , url(${props => props.bgmobile}) no-repeat center top;
}
`
class Heroes extends React.Component {
constructor(props) {
super(props);
...
render() {
return (
<Hero
bgdesktop={this.props.bgdesktop}
bgtablet={this.props.bgtablet}
bgmobile={this.props.bgmobile}/>
)}}然后我将这个组件添加到‘pages/Hero.js’中:
export default props => {
const hero = props.location.href
? heroCards.find(h => h.name === props.location.href.substring(28))
: heroCards[0]
return (
<Layout>
<Heroes
bgdesktop={require(`./../images/BG/${hero.name}_Desktop.jpg`)}
bgtablet={require(`./../images/BG/${hero.name}_Tablet.jpg`)}
bgmobile={require(`./../images/BG/${hero.name}_Mobile.jpg`)}
/>
</Layout>
)
}现在,点击主页上的不同按钮,我将重定向到不同的页面,这些页面根据heroes.js (位于costants文件夹中)中包含的“name”而采用不同的bg。它可以在本地运行,但不能在生产环境中运行,问题是gatsby不允许该'{require(./../images/BG/${hero.name}_Desktop.jpg)}'.我该如何解决这个问题?
发布于 2019-03-07 21:51:46
我不认为你需要require来解决这个问题。为什么不使用传递的属性,并将其烘焙成字符串文字,然后插入到组件中(不需要和在返回之外)?
const mobilePath = `./../images/BG/${props.bgmobile}_Mobile.jpg`;
const desktopPath = `./../images/BG/${props.bgdesktop}_Desktop.jpg`;
return(
<Heroes mobile={mobilePath} desktop={desktopPath} />
)编辑:在传递属性之前,可以在任一<Heroes>中添加substring部件。或者在<Hero>中过滤属性并传递该变量而不是属性
https://stackoverflow.com/questions/55044068
复制相似问题