如何在React应用程序中更新document.title?

Dan*_*mov 28 javascript dom reactjs react-router

由于React没有任何内置的管理方法document.title,我曾经在componentDidMount路由处理程序中设置它.

但是现在我需要根据state异步提取修改标题.我开始投入分配componentDidUpdate,但我时不时地忘记将document.title作业放到某些页面中,之前的标题一直存在,直到我终于注意到它为止.

理想情况下,我想要一种以document.title声明方式表达的方式,而不必分配它.鉴于我希望能够在几个嵌套级别指定文档标题,某种"假"组件可能是最方便的:

  • 在顶层(默认标题);
  • 在页面级别(对于某些页面,但不是全部);
  • 有时,在内部组件级别(例如,用户键入字段).

其他要求:

  • 子项中指定的标题应覆盖父项指定的标题;
  • 可靠(保证路线变更时的清理);
  • 不应该发出任何DOM(即没有组件返回的黑客<noscript>);
  • 我正在使用react-router,但如果这个组件也可以与其他路由器一起工作,那就更好了.

我能用什么?

Dan*_*mov 53

我为此写了反应文档标题.

它提供了一种document.title在单页面应用程序中指定的声明方式.
如果要在将组件呈现为字符串后获取服务器上的标题,请调用DocumentTitle.rewind().

特征

  • 不发出DOM,甚至不发出<noscript>;
  • 像普通的React组件一样,可以使用它的父级propsstate;
  • 可以在整个应用程序的许多地方定义;
  • 支持任意级别的嵌套,因此您可以定义应用程序范围和页面特定的标题;
  • 适用于客户端和服务器.

假设你使用像react-router这样的东西:

var App = React.createClass({
  render: function () {
    // Use "My Web App" if no child overrides this
    return (
      <DocumentTitle title='My Web App'>
        <this.props.activeRouteHandler />
      </DocumentTitle>
    );
  }
});

var HomePage = React.createClass({
  render: function () {
    // Use "Home" while this component is mounted
    return (
      <DocumentTitle title='Home'>
        <h1>Home, sweet home.</h1>
      </DocumentTitle>
    );
  }
});

var NewArticlePage = React.createClass({
  mixins: [LinkStateMixin],

  render: function () {
    // Update using value from state while this component is mounted
    return (
      <DocumentTitle title={this.state.title || 'Untitled'}>
        <div>
          <h1>New Article</h1>
          <input valueLink={this.linkState('title')} />
        </div>
      </DocumentTitle>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

资源

我跟踪已挂载的实例,并且只有在更新,挂载或卸载时才使用挂载的实例堆栈中title的顶层DocumentTitle.在服务器上,componentWillMount触发但我们不会得到didMountwillUnmount,因此我们引入DocumentTitle.rewind()它返回一个字符串并销毁状态以准备下一个请求.

var DocumentTitle = React.createClass({
  propTypes: {
    title: PropTypes.string
  },

  statics: {
    mountedInstances: [],

    rewind: function () {
      var activeInstance = DocumentTitle.getActiveInstance();
      DocumentTitle.mountedInstances.splice(0);

      if (activeInstance) {
        return activeInstance.props.title;
      }
    },

    getActiveInstance: function () {
      var length = DocumentTitle.mountedInstances.length;
      if (length > 0) {
        return DocumentTitle.mountedInstances[length - 1];
      }
    },

    updateDocumentTitle: function () {
      if (typeof document === 'undefined') {
        return;
      }

      var activeInstance = DocumentTitle.getActiveInstance();
      if (activeInstance) {
        document.title = activeInstance.props.title;
      }
    }
  },

  getDefaultProps: function () {
    return {
      title: ''
    };
  },

  isActive: function () {
    return this === DocumentTitle.getActiveInstance();
  },

  componentWillMount: function () {
    DocumentTitle.mountedInstances.push(this);
    DocumentTitle.updateDocumentTitle();
  },

  componentDidUpdate: function (prevProps) {
    if (this.isActive() && prevProps.title !== this.props.title) {
      DocumentTitle.updateDocumentTitle();
    }
  },

  componentWillUnmount: function () {
    var index = DocumentTitle.mountedInstances.indexOf(this);
    DocumentTitle.mountedInstances.splice(index, 1);
    DocumentTitle.updateDocumentTitle();
  },

  render: function () {
    if (this.props.children) {
      return Children.only(this.props.children);
    } else {
      return null;
    }
  }
});

module.exports = DocumentTitle;
Run Code Online (Sandbox Code Playgroud)

  • 亲爱的downvoter,你可以建议另一个解决这个问题的解决方案吗? (14认同)

raj*_*_kw 6

class Layout extends React.Component {
  constructor(props){
    super(props);
    document.title = this.props.title;
  }
  render(){
    return(
      <div>
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

然后<Layout title="My Title"/>那很容易!