gpt4 book ai didi

javascript - react : Is there something similar to node. 文本内容?

转载 作者:行者123 更新时间:2023-11-29 15:31:47 25 4
gpt4 key购买 nike

我正在尝试测试一个 react 组件的 child ,我想得到它的 child 的文本表示。

是否有工具可以为 React 执行类似于 node.textContent 的操作?

我想要这样的东西:

let testComponent = (
<Test>
<p>abc</p>
<p>abc2</p>
</Test>
);

expect(testComponent.props.children.toString()).to.equal('abc abc2');

最佳答案

react-getNodeText Sandbox screenshot

const getNodeText = node => {
if (['string', 'number'].includes(typeof node)) return node
if (node instanceof Array) return node.map(getNodeText).join('')
if (typeof node === 'object' && node) return getNodeText(node.props.children)
}

https://codesandbox.io/s/react-getnodetext-h21ss

  // in the picture
{heading} // <Heading>Hello <span className="red">Code</span>Sandbox</Heading>
<pre ref={printInnerHTML}/>
<pre>{getNodeText(heading)}</pre>

关于javascript - react : Is there something similar to node. 文本内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34204975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com