如何从 React 组件的渲染方法中获取纯文本或将 JSX.Element 转换为字符串?

Zhe*_*eng 2 javascript reactjs react-native

我想获取渲染方法的纯文本而不将其渲染到 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>
    }
}
Run Code Online (Sandbox Code Playgroud)

我没有找到可能的 React 或 ReactDom API 来完成这个要求。

Zhe*_*eng 5

我发现 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>
    }
}
Run Code Online (Sandbox Code Playgroud)