使用带有React组件的道具的样式组件

时间:2017-11-14 12:33:11

标签: reactjs styled-components

我在反应js项目中使用样式化组件。 在构造我的样式化组件img时,我希望背景依赖于组件获得的道具。 如果我正在构建一个功能组件,我只需使用:

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

在组件内部,它的工作原理。 但是我怎么能用类组件实现相同的呢?因为我不能在类本身内声明一个const var,而在它的一边,没有this.props

谢谢!

1 个答案:

答案 0 :(得分:6)

在组件范围之外定义时,您需要传入一个函数来访问 props 。所以在你的情况下:

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;
`;

styled-components遇到CSS模板中的某个功能时,它会使用分配给该组件的道具来调用它。

请记住,这是指分配给FramedImage组件的道具,因此如果您想从其父组件传入道具,则需要如此传播它们:

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