实现思路分析
在客户端对组件进行二次"渲染", 为组件元素附加事件.
客户端二次"渲染" hydrate
使用hydrate 方法对组件进行渲染, 为组件元素附加事件.
hydrate 方法在实现渲染的时候, 会复用原本已经存在的DOM 节点, 减少重新生成节点以及删除原本DOM 节点的开销.通过react-dom 导入hydrate.
//share同构代码 Home.js
import React from "react";
function Home() {
return <div onClick={
() => console.log("Hello")}>
Home works
</div>;
}
export default Home;
// clinet
import React from "react";
import ReactDOM from "react-dom";
ReactDOM.hydrate(
<Home/>,
document.getElementById("root")
);
客户端 webpack 打包,输出目录 public ,便于后面服务端静态访问此目录
//webpack.server.js
const path = require('path');
const nodeExternals = require('webpack-node-externals');
const config = {
mode: "development",
entry: './src/client/index.js',
output: {
path: path.join(__dirname, 'public')