我有一个问题:这是我的英雄组件
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中包含的'name'(位于costants文件夹中)。它适用于本地但不适用于生产,问题是盖茨比不允许'{require(./../ images / BG / $ {hero.name} _Desktop.jpg)}'。我怎么解决这个问题?
我认为你不需要require
。为什么不使用你传递的prop并将其烘焙到你插入组件的字符串文字中(没有require和返回之外)?
const mobilePath = `./../images/BG/${props.bgmobile}_Mobile.jpg`;
const desktopPath = `./../images/BG/${props.bgdesktop}_Desktop.jpg`;
return(
<Heroes mobile={mobilePath} desktop={desktopPath} />
)
编辑:substring
部分可以在通过道具之前加入<Heroes>
。或者通过过滤<Hero>
中的道具并传递该变量而不是道具