React具有客户端和服务器端呈现的同构组件

React isomorphic component with both client-side and server-side rendering

本文关键字:同构 组件 服务器端 客户端 React      更新时间:2023-09-26

我想创建一个具有客户端和服务器端渲染的react应用程序。

示例如下:

import styles from './Main.css';
import React, {Component} from 'react';
import Info from './Info/Info';
import Record from './Record/Record'
export default class Main extends Component {
    render() {
        return (
            <div className={styles.main}>
                <div className={styles.mainIn + ' clearfix'}>
                    <div className={styles.mainLeft}>
                        <Info info_num="2012201972"/>
                    </div>
                    <div className={styles.mainRight}>
                        <div className="clearfix mb20">
                            <Record />
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

在这个组件Main中,它需要在客户端呈现,除了<Record />

组件Record

import styles from './Record.css';
import layout from '../../shared/styles/layout.css'
import React, {Component} from 'react';
export default class Record extends Component {
    render() {
        return (
            <div className="float_two">
                <div className={layout.box + ' mr10'}>
                    This is Record!
                </div>
            <div>
        )
    }
}

我的问题是:

我搜索了一些使用ReactDom.renderToStringreact-router的服务器端渲染示例。但是,没有关于客户端和服务器端呈现的教程。

我想要实现的是,客户端首先加载并渲染组件<Main />,然后从服务器端加载<Record />

另一个问题是,如何加载样式模块记录。css与renderToString,因为我认为在这个renderToString只能加载html的东西,而不是css。

当人们提到服务器端渲染时,他们通常指的是顶层应用程序在某个路由上的初始渲染,而不是单个组件。

我很难理解你的用例是你所要求的。您的React应用程序是一个大型Fragments树,因此在服务器端呈现单个组件实际上没有意义。如果你想让Record成为React的一部分,那么客户端需要知道它,所以为什么不像往常一样在客户端渲染它呢?

如果你真的需要呈现它的服务器端,那么我猜你可以建立记录组件,使它做一个AJAX请求,然后返回的html可以使用https://facebook.github.io/react/tips/dangerously-set-inner-html.html呈现,但我不建议它。

我的猜测是,Record需要某种类型的数据从服务器端,这就是为什么你要渲染它在那里?相反,只需将该数据作为JSON获取并使用它来呈现组件客户端。


看了你的评论,我知道你想做什么。您想要的是从服务器动态加载内容(不是呈现html),以响应某些事件(向下滚动,单击按钮或其他)。React在这方面非常擅长。通过改变你的应用程序的状态(即记录有什么),React将有效地处理重渲染。

这是一个非常简单的应用。它开始有两个项目(foo和bar),应该呈现。为了响应一个动作(在本例中是单击按钮),更多的数据被加载到状态中,从而呈现给页面。您所需要做的就是修改它,这样您就可以通过AJAX调用后端来获取实际数据,而不是使用setTimeout

实时版本:https://codepen.io/dpwrussell/pen/qadrko

class Application extends React.Component {
  constructor(props) {
    super(props);
    // Start with 2 records
    this.state = {
      records: [
        {
          name: 'foo',
          description: 'Some foo'
        },
        {
          name: 'bar',
          description: 'Some bar'
        }
      ]
    };
    // Bind handlers
    this.loadMoreRecords = this.loadMoreRecords.bind(this);
  }
  // Method to call which gets more records on demand
  // Here I just use setTimeout and some static data, but in your case
  // this would be AJAX to get the data from your server where the callback
  // would do the setState. I use a 2 second delay to exaggerate a delay getting
  // the data from the server.
  loadMoreRecords() {
    setTimeout(() => {
      this.setState({
        records: this.state.records.concat([
          {
            name: 'hello',
            description: 'Some newly loaded hello'
          },
          {
            name: 'world',
            description: 'Some newly loaded world'
          }
        ])
      })
    }, 2000);
  }
  // Method to render whatever records are currently in the state
  renderRecords() {
    const { records } = this.state;
    return records.map(record => {
      return (
        <li>{ `${record.name} - ${record.description}` }</li>
      );
    })
  }
  // React's render method
  render() {
    return (
      <div>
        <h1>List of Records Page</h1>
        <ul>
          { this.renderRecords() }
        </ul>
        <input type='button' onClick={this.loadMoreRecords} value='Load more Records' />
      </div>
    );
  }
}
/*
 * Render the above component into the div#app
 */
ReactDOM.render(<Application />, document.getElementById('app'));

使用css-modules-require-hook。它类似于babel-register,但用于.css文件。基本上,它将require('Record.css')转换为基于钩子配置的javascript对象。所以你的hook配置应该和你的webpack css-loader配置一样。

把它放到服务器的入口文件中。

const hook = require('css-modules-require-hook');
hook({/* config */});