我正在尝试测试一个反应组件子级,我想获得其子级的文本表示。
有没有一个工具可以做类似的事情node.textContent
对于反应?
我想要这样的东西:
let testComponent = (
<Test>
<p>abc</p>
<p>abc2</p>
</Test>
);
expect(testComponent.props.children.toString()).to.equal('abc abc2');
// this is an out of date version, use the one below
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 https://codesandbox.io/s/react-getnodetext-h21ss
// in the screenshot above
const heading = <Heading>Hello <span className="red">Code</span>Sandbox</Heading>
return (
<div>
{heading}
<pre ref={printInnerHTML}/>
<pre>{getNodeText(heading)}</pre>
</div>
)
TypeScript 更新
const getNodeText = (node: React.ReactNode): string => {
if (node == null) return ''
switch (typeof node) {
case 'string':
case 'number':
return node.toString()
case 'boolean':
return ''
case 'object': {
if (node instanceof Array)
return node.map(getNodeText).join('')
if ('props' in node)
return getNodeText(node.props.children)
} // eslint-ignore-line no-fallthrough
default:
console.warn('Unresolved `node` of type:', typeof node, node)
return ''
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)