react 动态修改 document.title

装饰器

// withComponents/withHeaderBar.js

import React, { Component } from "react";
import HeaderBar from "../components/headerAppBar";
const l = console.log;
const styles = {
  root: {
    marginTop: "3rem",
  },
};

export default function withHeaderBar({
  title,
  children,
  position,
  component = true,
}) {
  return function(Target) {
    return class WithHeaderBar extends Component {
      componentWillMount() {
        // document.title = title;
        setTitle(title);
      }
      render() {
        const style = position === "fixed" ? styles.root : {};
        return component ? (
          <div style={{ ...style }}>
            <HeaderBar title={title} children={children} position={position} />
            <Target {...this.props} />
          </div>
        ) : (
          <Target {...this.props} />
        );
      }
    };
  };
}
function setTitle(t) {
  document.title = t;
  var iframe = document.createElement("iframe");
  iframe.style.visibility = "hidden";
  iframe.setAttribute("src", "favicon.ico");
  var iframeCallback = function() {
    setTimeout(function() {
      iframe.removeEventListener("load", iframeCallback);
      document.body.removeChild(iframe);
    }, 0);
  };
  iframe.addEventListener("load", iframeCallback);
  document.body.appendChild(iframe);
}

使用

@withHeaderBar({
  title: "附近优惠",
  position: "fixed",
})
class NearbyOffers extends Component {
  render() { ... }
}
posted @ 2018-12-01 16:31  Ajanuw  阅读(2115)  评论(0编辑  收藏  举报