React17使用styled-components传props设置背景图失效如何解决
问题原因与解决方案
问题原因
你传递组件属性的写法不符合React语法规范:所有需要传递给组件的自定义属性,必须写在组件的起始标签内部,而不是写在<Component>和</Component>的包裹区间。你当前写在Section标签包裹区间的title='Top Model'这类内容,会被统一识别为children属性值,不会作为独立props传递给Section组件,所以你解构获取的所有属性都是undefined。
解决方案
修改LandingPage中Section组件的调用写法,把所有属性移到<Section>起始标签中即可:
function LandingPage (){ return( <Container> <Section title='Top Model' desc='My Description' leftBtn='Buy' rightBtn='Add to Cart' bgImg='car.jpg' ></Section> </Container> ) } export default LandingPage; const Container = styled.div` height: 100vh;`
验证方法
修改完成后重新运行项目,你可以在Section组件中添加打印语句验证属性传递是否正常:
function Section ({title, desc, leftBtn, rightBtn, bgImg}){ console.log(title, desc, bgImg) // 浏览器控制台会输出对应参数值 return ( <Wrap bg={bgImg}></Wrap> ) }
此时检查元素也能看到背景图属性正常渲染为background-image: url("/images/car.jpg");。
内容的提问来源于stack exchange,提问作者Abhishek Chokra
相关产品推荐
相关产品推荐

