React:有没有类似于 node.textContent 的东西?

Ala*_*uza 8 javascript unit-testing reactjs

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

有没有类似node.textContentReact的工具?

我想要这样的东西:

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

expect(testComponent.props.children.toString()).to.equal('abc abc2');
Run Code Online (Sandbox Code Playgroud)

Qwe*_*rty 9

react-getNodeText 沙盒截图

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)
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

  • 对于那些像我一样对“typeof node === 'object' &amp;&amp; node”感到困惑的人,“null”的类型是“object”,因此此检查可以防止 null。 (4认同)

yon*_*nmn 0

您可以使用getDomNode()findDomNode(),然后使用普通的 DOM 方法。

如果你正在寻找 React 方式 - 不应该有这样的方式,因为父母对其孩子非常盲目。