[英]How to get the length of the text inside the React component
I have React component, where I have some dynamic text: 我有React组件,其中有一些动态文本:
...
let spanLength
return(
<SomeComp>
...
<span>Some static text: {someDynamicText}, {someAnotherText}</span>
...
</SomeComp>
)
How can I get the length of text inside span
element to a spanLength
variable? 如何获取
span
元素内的文本长度到spanLength
变量?
Why not, first, compose the whole string? 为什么不首先组成整个字符串呢? You can grab its length immediately after, and then render it.
您可以在之后立即获取其长度,然后进行渲染。
const spanStr = `Some static text: ${someDynamicText}, ${someAnotherText}`;
const spanLength = spanStr.length;
return(
<SomeComp>
...
<span>{spanStr}</span>
...
</SomeComp>
)
You can add a ref
to your span
您可以在
span
添加ref
let spanRef = React.createRef()
...
<span ref={spanRef}>Some static text: {someDynamicText}, {someAnotherText}</span>
Then the text length would simply be spanRef.current.textContent.length
然后,文本长度将只是
spanRef.current.textContent.length
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.