首页 > 解决方案 > 渲染道具时导致意外行为的样式化组件

问题描述

我有一个 WhiteBox react 组件,它简单地呈现一个带有一些样式的白框。我有一个 SmallBox 反应组件,它只是使用 WhiteBox 来呈现更具体的框。我有一个 Content react 组件,它呈现三个 SmallBox 框,它们完成了它应该做的事情(呈现三个白框)。但是,当我尝试从父级添加文本作为道具时,白框与顶部的一些意外边距对齐。注意:当我简单地输入“这是一个文本”时,css 没问题,但是当我将“这是一个文本”作为 props.text 发送时,白框会从顶部以额外的边距呈现。我使用 styled-components 并按照我所说的做出反应。

我试图 console.log 文本,一切似乎都很好。我也尝试切换 props.children 或 props.text 并不起作用

-----------------白盒组件----------------------

import styled from "styled-components";

const StyledBox = styled.div`
  display: inline-block;
  width: ${props => props.width}px;
  height: ${props => props.height}px;
  margin-right: ${props => props.marginRight}px;
  margin-left: 100px;
  background-color: white;
  border-radius: 5px;

  font-size: 13px;
  font-weight: 700;
  text-transform: uppercase;
  color: #646777;
  padding: 10px;
`;
const WhiteBox = props => {
  return (
    <StyledBox
      width={props.width}
      height={props.height}
      marginRight={props.marginRight}
    >
      {props.text} // if I change this to simply "this is a text" it works well. somehow the props.text is causing problems.
    </StyledBox>
  );
};

export default WhiteBox;```

-----------------Small Box Component ----------------------

import React from "react";
import styled from "styled-components";
import WhiteBox from "../whitebox/white-box";

const SmallBox = props => {
  return (
    <WhiteBox width={320} height={130} marginRight={70} marginLeft={70} text={props.text}>
    </WhiteBox>
  );
};

export default SmallBox;


-----------------Content Component ----------------------


import React, { Component } from "react";
import SmallBox from "./smallbox/small-box";

import styled from "styled-components";

const StyledContent = styled.div`
  position: absolute;
  left: 320px;
  top: 80px;
  width: 100%;
  height: 100%;
  background-color: #f1f3f7;
`;


class Content extends Component {
  render() {
    return (
      <>
        <StyledContent>
          <SmallBox text="this text is great" /> // causing problem
          <SmallBox />
          <SmallBox />
        </StyledContent>
      </>
    );
  }
}

export default Content;

标签: reactjsstyled-components

解决方案


这个问题与渲染了多少行有关。道具中的文字越长,渲染的线条越多。

一种解决方案是更改displayWhiteBox 的属性:

const StyledBox = styled.div`
  display: inline-flex;
  ....
`;

另一种解决方案是覆盖默认样式vertical-align: baseline,只需添加vertical-align: top;

const StyledBox = styled.div`
  display: inline-block;
  ....
  vertical-align: top;
`;

推荐阅读