react-routers 如何同时渲染两个位置?

  • 主要是两个问题:

  • 架构是 express+swig_nodejs+react+react-router

  1. 请大家看 index.html,我想同时渲染 <title><body> 里的一个位置,如何传递 <title> 的值?希望这个值可以由 react.js 动态给出

  2. 第二个问题是如何选择性的渲染 index.html 和另一个 html 模板,比如我想让访问 /index 时渲染用 App-Index 这个组件渲染 index.html,然后访问 /regist 时用 App-Regist 渲染 regist.html

this is the server.js about router settings:

app.use(function(req, res) {
  Router.run(routes, req.path, function(Handler) {
    var html = React.renderToString(React.createElement(Handler));
    var page = swig.renderFile('views/index.html', { html: html});
    res.send(page);
  });
});

this is the /app/routes.js:

import React from 'react';
import {Route} from 'react-router';
import App from './components/App';
import Home from './components/Home';
import Regist from './components/Regist';

export default (
  <Route handler={App}>
    <Route path='/' handler={Home} />
    <Route path='/regist' handler={Regist} />
  </Route>
);

this is the /app/main.js:

import React from 'react';
import Router from 'react-router';
import routes from './routes';

Router.run(routes, Router.HistoryLocation, function(Handler) {
  React.render(<Handler />, document.getElementById('app'));
});

this is the /app/App.js:

import React from 'react';
import {RouteHandler} from 'react-router';

class App extends React.Component {
  render() {
    return (
        <RouteHandler />
    );
  }
}

export default App;

this is the /view/index.html, I want to set {{title}} and {{html|safe}} at the same time

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>{{title}}</title>
    <link rel="stylesheet" href="/css/amazeui.css"/>

  </head>
  <body>
    <div id="app">{{ html|safe }}</div>
    <script src="/socket.io/socket.io.js"></script>
    <script src="/js/vendor.js"></script>
    <script src="/js/vendor.bundle.js"></script>
    <script src="/js/bundle.js"></script>
  </body>
</html>
阅读 4.5k
1 个回答

如果想要修改 title 的话推荐使用 react sideeffects 相关的组件,GitHub 上面都有自己可以搜一下

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题