如何将React.Component与renderToString方法一起使用?

时间:2018-12-18 04:11:06

标签: reactjs serverside-rendering isomorphic-javascript ssr render-to-string

我尝试使用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

0 个答案:

没有答案
相关问题