如何使用React.Component与renderToString方法?(How to use R

2019-10-28 17:36发布

我试图做服务器端渲染使用renderToString方法。

function handleRender(req, res) {

    const html = renderToString(
        <Counter />
    );

    res.send(renderFullPage(html));
}

function renderFullPage(html) {
  return `
    <!doctype html>
    <html>
      <head>
        <title>React Universal Example</title>
      </head>
      <body>
        <div id="app">${html}</div>
        <script src="/static/bundle.js"></script>
      </body>
    </html>
    `
}

如果像下面的某个组件的工作原理:

Counter.js

const Counter = () => {

  function testClick(){
    console.log('test');
  }

  return (
    <div>
      <div onClick={testClick.bind(this)}>
        test
      </div> 
    </div>
  );

};

export default Counter;

但是,如果我改变Counter.js到以下几点:

class Counter extends React.Component {

    testClick(){
        console.log('click');
    }

    render() {
        return (
            <div>
                <div onClick={this.testClick.bind(this)}>
                    test btn
                </div>
            </div>
        )
    }
}

export default Counter;

它会显示错误:

Uncaught Error: locals[0] does not appear to be a `module` object with Hot Module replacement API enabled. You should disable react-transform-hmr in production by using `env` section in Babel configuration.

因此,如何使用React.Component与renderToString方法?


我尽量减少项目,并推到Github上。 请看一看。

https://github.com/ovojhking/ssrTest/tree/master

文章来源: How to use React.Component with renderToString method?