admin 管理员组文章数量: 1086019
I want to get the plain text of a render method without rendering it into DOM:
class Test from React.Component {
getPlainText = () => {
const plainText = /* some method */(this.renderParagraph())
console.log(plainText) // output in console: <p>I'm text from props of Text ponent!</p>
}
renderParagraph () {
return <p>{this.props.text}</p>
}
render () {
return <button onClick={this.getPlainText}>click me will print {this.props.text} in console</button>
}
}
I didn't find a possible React or ReactDom API to acplish this requirement.
I want to get the plain text of a render method without rendering it into DOM:
class Test from React.Component {
getPlainText = () => {
const plainText = /* some method */(this.renderParagraph())
console.log(plainText) // output in console: <p>I'm text from props of Text ponent!</p>
}
renderParagraph () {
return <p>{this.props.text}</p>
}
render () {
return <button onClick={this.getPlainText}>click me will print {this.props.text} in console</button>
}
}
I didn't find a possible React or ReactDom API to acplish this requirement.
Share Improve this question edited Jan 21, 2018 at 11:44 Zheeeng asked Jan 19, 2018 at 3:21 ZheeengZheeeng 68210 silver badges22 bronze badges 3- it's actually unclear what you want to do with that text – kg2152 Commented Jan 19, 2018 at 3:37
- There are many mistakes in your code. – Hemadri Dasari Commented Jan 19, 2018 at 4:04
- @kg2152 as example shows, I need to log out the stringify html. More accurately, we can feed these text to a keywords parsers, table to excel converter, html structure displayer. – Zheeeng Commented Jan 21, 2018 at 11:50
1 Answer
Reset to default 7I find that ReactDOMServer.renderToString provides this feature.
import ReactDOMServer from 'react-dom/server'
class Test from React.Component {
getPlainText = () => {
const plainText = ReactDOMServer.renderToString(this.renderParagraph())
console.log(plainText) // output in console: <p>I'm text from props of Text ponent!</p>
}
renderParagraph () {
return <p>{this.props.text}</p>
}
render () {
return <button onClick={this.getPlainText}>click me will print {this.props.text} in console</button>
}
}
本文标签:
版权声明:本文标题:javascript - How can I get the plain text from the render method from React component or convert a JSX.Element to string? - Stac 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744067306a2527840.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论