How to use React.Component with renderToString method?

眉间皱痕 提交于 2019-12-12 01:25:44

问题


I tried to do the server side render using renderToString method.

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

If the component like following it works:

Counter.js

const Counter = () => {

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

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

};

export default Counter;

However, if I change Counter.js into following:

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;

It will show errors:

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.

So how to use React.Component with renderToString method?


I minimize the project and push to Github. Please have a look.

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

来源:https://stackoverflow.com/questions/53826283/how-to-use-react-component-with-rendertostring-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!