如何使用 React 在服务器端渲染图像和 css 文件?
这是我的服务器代码:
const express = require('express')
const router = express.Router()
const ReactDOM = require('react-dom/server');
import Master from '../../../client/Master'
router.get('/', (req, res) => {
res.render('test.html', {reactOutput: ReactDOM.renderToString(<Master/>)});
});
主组件:
import React from "react";
import Intro from "./pages/Intro";
import Footer from "./components/Footer";
import Header from "./components/Header";
export default class Master extends React.Component {
constructor() {
super();
this.state = {appStatus: 'INTRO'}
}
render() {
let layout;
switch (this.state.appStatus) {
case "INTRO":
layout = <Intro/>;
}
return (
<div>
<Header/>
{layout}
<Footer/>
</div>
)
}
}
但是当我用 babel 运行服务器时,我收到了这个错误:
/assets/img/logo.png: 意外字符 '?' (1:0)
这是 Header 组件,它试图要求徽标。
import React from "react";
**import logo from '../../assets/img/logo.png';**
export default class Header extends React.Component {
constructor() {
super();
}
render() {
return (
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">**<img width="250" src={logo} alt=""/></a>**
</div>
</div>
</nav>
);
}
}
但是它在客户端的 webpack 中工作得很好..