我有React组件,其中有一些动态文本:
...
let spanLength
return(
<SomeComp>
...
<span>Some static text: {someDynamicText}, {someAnotherText}</span>
...
</SomeComp>
)
如何将span
元素内的文本长度转换为spanLength
变量?
答案 0 :(得分:6)
为什么不首先组成整个字符串?您可以在之后立即获取其长度,然后进行渲染。
const spanStr = `Some static text: ${someDynamicText}, ${someAnotherText}`;
const spanLength = spanStr.length;
return(
<SomeComp>
...
<span>{spanStr}</span>
...
</SomeComp>
)
答案 1 :(得分:5)
您可以将ref
添加到span
let spanRef = React.createRef()
...
<span ref={spanRef}>Some static text: {someDynamicText}, {someAnotherText}</span>
然后,文本长度将简单地为spanRef.current.textContent.length