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

本文标签:

Error[2]: Invalid argument supplied for foreach(), File: /www/wwwroot/roclinux.cn/tmp/view_template_quzhiwa_htm_read.htm, Line: 58
File: /www/wwwroot/roclinux.cn/tmp/route_read.php, Line: 205, include(/www/wwwroot/roclinux.cn/tmp/view_template_quzhiwa_htm_read.htm)
File: /www/wwwroot/roclinux.cn/tmp/index.inc.php, Line: 129, include(/www/wwwroot/roclinux.cn/tmp/route_read.php)
File: /www/wwwroot/roclinux.cn/index.php, Line: 29, include(/www/wwwroot/roclinux.cn/tmp/index.inc.php)