【问题标题】:conditional width sizing with styled components带有样式组件的条件宽度大小
【发布时间】:2020-02-25 15:19:47
【问题描述】:
import styled from 'styled-components';
<SubTitle length={this.state.name}>{this.state.name}</SubTitle>

我将随机字符串发送到this.state.name, 并且取决于字符串长度,我喜欢设置宽度大小。

const SubTitle = styled.h1`
  font-size: 1.2rem;
  margin: 20px;
  font-weight: bolder;
  background-color: rgba(250, 250, 250, 0.5);
  width: ${async props => {
    let len;
    if (props.length) {
      len = await props.length.length;
    }
    return `${len}rem`;
  }};

我试过了,但它不起作用。

【问题讨论】:

  • 您确定要使用length 作为道具名称吗?它很容易与字符串和数组等内置类型的length 属性混淆。
  • 你可以使用`width: max-content`

标签: css reactjs width


【解决方案1】:

你可以尝试使用 -

import styled, { css } from "styled-components";

${props => (props.length ? css`
  width: //change the logic to whatever you want
` : css`
  width: //whatever default width
`)}

【讨论】:

    猜你喜欢
    • 2018-10-16
    • 2018-01-23
    • 1970-01-01
    • 2019-02-24
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    相关资源
    最近更新 更多