[英]How can I get the plain text from the render method from React component or convert a JSX.Element to string?
我想獲取一個render方法的純文本而不將其渲染到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 component!</p>
}
renderParagraph () {
return <p>{this.props.text}</p>
}
render () {
return <button onClick={this.getPlainText}>click me will print {this.props.text} in console</button>
}
}
我找不到可能的React或ReactDom API來滿足此要求。
我發現ReactDOMServer.renderToString提供了此功能。
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 component!</p>
}
renderParagraph () {
return <p>{this.props.text}</p>
}
render () {
return <button onClick={this.getPlainText}>click me will print {this.props.text} in console</button>
}
}
您忘記在getPlainText()方法中添加“ =>”
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 component!</p>
}
renderParagraph () {
return <p>{this.props.text}</p>
}
render () {
return <button onClick={this.getPlainText}>click me will print {this.props.text} in console</button>
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.