0

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

如果像下面这样的组件可以工作:

计数器.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.

那么如何使用带有 renderToString 方法的 React.Component 呢?


我将项目最小化并推送到 Github。请看一看。

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

4

0 回答 0