简体   繁体   English

反应获取组件内的文本

[英]React get Text inside of component

I want to get the text content of the react element.我想获取 react 元素的文本内容。 In the example below, I want get: hello 1在下面的例子中,我想得到: hello 1

var node = <myComponent id={1} />

class myComponent extends React.Component {

render() {
  return {
    <span> hello {this.props.id} </span>
  }
}

I tried to use node.text or ReactDOM.findDOMNode(node).textContent , but it doesn't work.我尝试使用node.textReactDOM.findDOMNode(node).textContent ,但它不起作用。 Can I get some help?我能得到一些帮助吗?

Thanks!谢谢!

嗨,我认为你应该像下面这样修改你的代码:

<myComponent id={1} />

Try calling your code using:尝试使用以下方法调用您的代码:

ReactDOM.render(<MyComponent id={1} />, document.getElementById("root"));

Your code:您的代码:

class MyComponent extends React.Component {
  render() {
    return <span>Hello {this.props.id}</span>;
  }
}

Link to this code in a Codesandbox: https://codesandbox.io/s/class-component-dv6fj在 Codesandbox 中链接到此代码: https ://codesandbox.io/s/class-component-dv6fj

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM