最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I get the plain text from the render method from React component or convert a JSX.Element to string? - Stac

programmeradmin10浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 7

I 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>
    }
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论