使用样式组件的条件宽度调整大小

问题描述 投票:0回答:1
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`;
  }};

我尝试了这个,但是没有用。

css reactjs width
1个回答
0
投票

您可以尝试使用-

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

${props => (props.length ? css`
  width: ${props.length.length}px; //change the logic to whatever you want
` : css`
  width: 100%; //whatever default width
`)}
© www.soinside.com 2019 - 2024. All rights reserved.