简体   繁体   中英

Using styled-components with props from React component

I'm using styled components in my react js project. when constructing my styled component img, I want the background to be dependent on the props the component gets. If i'm building a functional component I just use:

  const FramedImage = styled.img`
  background-size: cover;
  background: URL(${props.imageUrl});
  background-position: center center;
  background-repeat: no-repeat;`;

inside the component and it works. but how can I achieve the same with class components? since I can't declare a const var inside the class itself, and out side of it, there is no this.props

Thanks!

You need to pass in a function to access props when defined outside the scope of the component. So in your case:

const FramedImage = styled.img`
  background-size: cover;
  background: URL(${props => props.imageUrl}); //use a function here instead
  background-position: center center;
  background-repeat: no-repeat;
`;

When styled-components encounters a function in the CSS template, it'll call it with the props assigned to the component.

Remember though this is refers to props assigned to the FramedImage component, so if you want to pass in props from it's parent component, you need to spread them in as such:

class Parent extends React.Component {
  render() {
    return <FramedImage {...this.props} />
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM