Syled Components Background Image React

◇◆丶佛笑我妖孽 提交于 2021-01-29 10:57:24

问题


I am trying to pass a background image through a prop and it's not working, it's saying that url is undefined.

const CardImage = styled.div`
        height: auto;
        width: 100%;
        background-size: contain;
        background: url(${props => props.data.url});  
    `
function Card(props) {
    return (
        <CardImage/>
    )
}

<Card data={{url: "https://via.placeholder.com/150x150", text: "test"}}/>

回答1:


You are never passing the props from Card to <CardImage/>:

function Card(props) {
  return <CardImage {...props} />;
}



回答2:


 function Card(props) {
  const style = {
    height: "150px",
    width: "150px",
    backgroundImage: `url(${props.data.url})`,
    backgroundRepeat: "no-repeat"
  };
  return <div style={style}>Background</div>;
}


来源:https://stackoverflow.com/questions/58617591/syled-components-background-image-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!