Javascript 检查p中的文本行数并存储在变量中
我有一个表,其中有一列名为“comments”。 在特定单元格中,只有当文本超过2行时,我才想:Javascript 检查p中的文本行数并存储在变量中,javascript,reactjs,Javascript,Reactjs,我有一个表,其中有一列名为“comments”。 在特定单元格中,只有当文本超过2行时,我才想: 呈现显示“显示更多”的可单击文本 将文本线夹为两行 目前,我在每个单元中都有一个线夹,如下所示: const ClampedText = styled.p` display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; `; 此元素的使用方式如下: {de
- 呈现显示“显示更多”的可单击文本
- 将文本线夹为两行
const ClampedText = styled.p`
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
`;
此元素的使用方式如下:
{description}
其中description
是单元格中的文本
使用样式化组件
我主要想做的是得到一个布尔变量,说明在一个特定的p中是否有两行以上的文本,然后有条件地相应地渲染组件(有/没有“show more”和线夹)
如何做到这一点
创意
“comments”列的宽度为表的10%,因此我认为它可以与som JS一起使用,并计算将要显示的行数。由于文本行数可以根据屏幕大小而不同,因此可以检查字符串长度以了解以下情况:
const ClampedText = (props) => {
const [isExpanded, setIsExpanded] = useState(false);
const expander = () => {
if(props.children.toString().length >= 200){
setIsExpanded(!isExpanded);
}
}
return (
<div onClick={() => expander()}} className={isExpanded ? 'expanded' : ''}>
<p>
{props.children.toString().length < 200 ?
props.children.toString() :
(isExpanded? props.children.toString(): props.children.toString().substr(0,200) + '...') }
</p>
</div>
)
}
const ClampedText=(道具)=>{
常量[isExpanded,setIsExpanded]=useState(false);
常数扩展器=()=>{
if(props.children.toString().length>=200){
setIsExpanded(!isExpanded);
}
}
返回(
expander()}className={isExpanded?'expanded':''}>
{props.children.toString()。长度<200?
props.children.toString():
(isExpanded?props.children.toString():props.children.toString().substr(0200)+’…)}
)
}
由于文本行数可以根据屏幕大小而不同,因此您可以检查字符串长度以了解以下情况:
const ClampedText = (props) => {
const [isExpanded, setIsExpanded] = useState(false);
const expander = () => {
if(props.children.toString().length >= 200){
setIsExpanded(!isExpanded);
}
}
return (
<div onClick={() => expander()}} className={isExpanded ? 'expanded' : ''}>
<p>
{props.children.toString().length < 200 ?
props.children.toString() :
(isExpanded? props.children.toString(): props.children.toString().substr(0,200) + '...') }
</p>
</div>
)
}
const ClampedText=(道具)=>{
常量[isExpanded,setIsExpanded]=useState(false);
常数扩展器=()=>{
if(props.children.toString().length>=200){
setIsExpanded(!isExpanded);
}
}
返回(
expander()}className={isExpanded?'expanded':''}>
{props.children.toString()。长度<200?
props.children.toString():
(isExpanded?props.children.toString():props.children.toString().substr(0200)+’…)}
)
}
您可以使用string.length
了解长度,并决定是否显示显示更多链接。
这是上面的完整代码
const[段落,设置段落]=useState({
show:null,
第段:“,
单击:false
});
...
返回(
{段落.段落}
段落({
秀:没错,
单击:!段落。单击,
段落:段落.点击
?dummyText.子字符串(0,25).concat(“…”)
:dummyText
})
}
>
{段落.clicked?“显示较少”:“显示较多”}
);
您可以使用string.length
了解长度,并决定是否显示显示更多链接。
这是上面的完整代码
const[段落,设置段落]=useState({
show:null,
第段:“,
单击:false
});
...
返回(
{段落.段落}
段落({
秀:没错,
单击:!段落。单击,
段落:段落.点击
?dummyText.子字符串(0,25).concat(“…”)
:dummyText
})
}
>
{段落.clicked?“显示较少”:“显示较多”}
);
。。