reactjs - 渲染道具时导致意外行为的样式化组件
问题描述
我有一个 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;
解决方案
这个问题与渲染了多少行有关。道具中的文字越长,渲染的线条越多。
一种解决方案是更改display
WhiteBox 的属性:
const StyledBox = styled.div`
display: inline-flex;
....
`;
另一种解决方案是覆盖默认样式vertical-align: baseline
,只需添加vertical-align: top;
const StyledBox = styled.div`
display: inline-block;
....
vertical-align: top;
`;
推荐阅读
- python - 为什么 Pytorch autograd 需要另一个向量来向后而不是计算雅可比?
- android - Firebase 手机身份验证和华为应用程序库
- r - sil.obj[, 1:3] 中的错误:剪影方法的维数不正确?
- powerapps - PowerApps 无法将集合修补为表
- cuda - CUDA Profiler 中“flop_count_sp”和“inst_fp_32”指标的含义
- mongodb - 如何使用 bson 使用 golang 更新 MongoDB 中的特定嵌套结构字段
- python - 当网络抓取链接时,Python 请求模块工作异常
- android - Kotlin 中视图的 EditText 绑定不起作用
- angular - 为什么使用 @rollup/plugin-node-resolve 时 Typescript 注释不起作用?
- php - 如何在使用 scandir() 时跳过我无权读取/访问的文件,以避免所有记录的错误?