React:有没有类似于 node.textContent 的东西? [英] React: Is there something similar to node.textContent?

查看:43
本文介绍了React:有没有类似于 node.textContent 的东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试一个 react 组件的孩子,我想获得其孩子的文本表示.

I'm trying to test a react component children and I wanted to get a text representation of its children.

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

Is there a tool that does something similar to node.textContent for React?

我想要这样的东西:

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

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

推荐答案

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>

这篇关于React:有没有类似于 node.textContent 的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆