【问题标题】:Can styled components handle computations like SCSS?样式化的组件可以处理像 SCSS 这样的计算吗?
【发布时间】:2018-09-02 10:58:53
【问题描述】:

使用 SCSS,我可以像这样创建 CSS 魔法:

@for $i from 1 through $total-items {
  li:nth-child(#{$i}) {
    animation-delay: .25s * $i;
  }
}

我现在正在开发一个使用样式化组件的 React 应用程序。样式化的组件是否以某种方式允许上述情况?

【问题讨论】:

  • 你可以用javascript做同样的事情,去掉中间人

标签: css reactjs sass styled-components


【解决方案1】:

您可以去掉中间人并在渲染期间进行计算,或者您可以将索引传递给返回将生成您的样式的对象的东西。

totalItems.map((item, index) => {
   <li style={animationDelay: `${.25 * index}s`}>{item.name}</li>
})

否则你可以创建样式并传入索引来创建样式对象

const style = (index) => {
  return {
    animationDelay: `${.25 * index}s`
  }
}

但是,如果您正在寻找样式化的组件方式 在此处传递您的组件,其 attr 为 index={the index of the item}

const StyledLink = styled(component here)`
    animationDelay: ${props => props.index};
`;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-21
    • 2011-01-13
    • 2018-12-30
    • 2020-05-20
    • 1970-01-01
    • 2014-01-02
    • 2023-02-26
    • 2020-04-24
    相关资源
    最近更新 更多