重新加载后,样式化组件会丢失样式

时间:2018-09-05 01:11:37

标签: reactjs styled-components

我首先渲染了模板服务器端,并且在初始加载时一切似乎都可以正常工作。但是在开发中,一旦我更改了样式化的组件的样式并重新加载,该组件就会丢失其所有样式。奇怪的是,如果我将其更改回原始样式,样式将返回并将其附加到元素。有人知道为什么会这样吗?

Webpack.config.js

const path = require('path');
module.exports = {
  entry: path.join(__dirname, 'client/index.js'),
  output: {
    path: path.join(__dirname, 'client-build'),
    filename: 'client.bundle.js',
    publicPath: path.join('testapp', 'static'),
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [path.resolve(__dirname, 'client')],
        exclude: /node_modules/,
        options: {
          babelrc: true,
        },
      },
      {
        test: /\.pcss$/,
        use: [
          {
            loader: 'style-loader',
            options: {hmr: true},
          },
        ],
      },
      {
        test: /\.(html)$/,
        loader: 'html-loader',
      },
    ],
  },
};

package.json脚本在使用Webpack时监视客户端src

"dev:client": "webpack --watch --mode=development --progress",

server.js

...

app.use(async (ctx) => {
  ctx.type = 'text/html';
  ctx.body = `<!DOCTYPE html><html><head></head><body><div id='root'>
  ${renderToString(<App><div>This is render from the server-side template</div></App>)}
  </div></body><script src="/testapp/static/client.bundle.js"></script></html>`;
});
app.listen(port);

client / index.js

import React from 'react';
import {hydrate} from 'react-dom';

import {App} from './components';

hydrate(
  <App>
    <div>This is render from the client-side</div>
  </App>,
  document.getElementById('root')
);

例如styled-component> App Component

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';

const PropTypes = {
  children: PropTypes.element.isRequired,
};

const App = ({children}) => (
  <Container>
    {children}
  </Container>
);

App.propTypes = PropTypes;
export default App;

const Container = styled.div`
  display: flex;
  height: 90%;
  background: yellow;
`;

0 个答案:

没有答案