[英]How to get the length of the text inside the React component
我有React組件,其中有一些動態文本:
...
let spanLength
return(
<SomeComp>
...
<span>Some static text: {someDynamicText}, {someAnotherText}</span>
...
</SomeComp>
)
如何獲取span
元素內的文本長度到spanLength
變量?
為什么不首先組成整個字符串呢? 您可以在之后立即獲取其長度,然后進行渲染。
const spanStr = `Some static text: ${someDynamicText}, ${someAnotherText}`;
const spanLength = spanStr.length;
return(
<SomeComp>
...
<span>{spanStr}</span>
...
</SomeComp>
)
您可以在span
添加ref
let spanRef = React.createRef()
...
<span ref={spanRef}>Some static text: {someDynamicText}, {someAnotherText}</span>
然后,文本長度將只是spanRef.current.textContent.length
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.