【问题标题】:Using styled-components with props from React component使用带有来自 React 组件的 props 的 styled-components
【发布时间】:2018-04-27 09:58:30
【问题描述】:

我在我的 react 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

谢谢!

【问题讨论】:

  • 你可以在类范围之外声明 const 或 let ..并在类内使用
  • 但是如何在类外的 const 声明中使用 this.props

标签: reactjs styled-components


【解决方案1】:

当在组件范围之外定义时,您需要传入一个函数来访问 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 模板中遇到一个函数时,它会使用分配给组件的 props 调用它。

记住虽然这是指分配给FramedImage组件的props,所以如果你想从它的父组件传入props,你需要传播它们像这样:

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

【讨论】:

    猜你喜欢
    • 2018-04-15
    • 2019-02-18
    • 2019-03-14
    • 2021-05-01
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 2021-09-22
    • 2017-12-21
    相关资源
    最近更新 更多