样式化的组件在渲染道具时导致意外行为

时间:2019-03-25 07:40:27

标签: reactjs styled-components

我有一个WhiteBox react组件,可以简单地渲染具有某些样式的白盒。 我有一个SmallBox react组件,它仅使用WhiteBox来呈现更特定的框。 我有一个Content react组件,它呈现三个SmallBox框,该框完成了应做的工作(提供三个白框)。 但是,当我尝试从父级添加文本作为道具时,白框与顶部的某些意外边距对齐。 注意:当我简单地输入“ This is a text”时,css是可以的,但是当我发送“ this is a text”作为props.text时,白框从顶部开始具有额外的空白。 我使用样式化组件并按照我所说的进行反应。

我尝试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;

1 个答案:

答案 0 :(得分:1)

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

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

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

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

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