【问题标题】:Update document title by props from child component通过子组件中的道具更新文档标题
【发布时间】:2018-03-19 19:35:07
【问题描述】:

我的应用中有主组件,我有设置文档标题的方法。组件看起来像:

class Main extends React.Component {
  componentWillMount() {
    this.setTitle(this.props.title);
  }

  componentWillReceiveProps(newProps) {
    if (newProps.title !== this.props.title) {
      this.setTitle(newProps.title);
    }
  }

  setTitle = (title) => {
    document.title = title;
  };

  render() {
    const { children } = this.props;

    return (
      <div>
        {children}
      </div>
    );
  }
}

export default Main;

用法:

class App extends Component {
  render() {
    return <Main><AppContent /></Main>;
  }
}

现在我想在子组件(AppContent 和该组件的子组件)中设置文档标题。问题是我在故事书 repo 中有 Main 组件,我不能在 Main 组件的索引文件中使用 redux(我可以在 App 组件和其他组件中这样做,但我以前从未使用过 redux)。任何人都可以给我一个提示,我应该如何从其他组件传递标题? 问候

【问题讨论】:

    标签: javascript reactjs ecmascript-6 redux


    【解决方案1】:

    为了以一种干净利落的方式实现这一点,我使用了 NFL 的 react-helmet(是的 NFL)。

    https://github.com/nfl/react-helmet

    使用react-helmet,您可以在任何子组件中执行以下操作,嵌套在任何级别:

    import { Helmet } from "react-helmet"
    
    <ChildComponent>
        <Helmet>
            <title>react-helmet will make this the title</title>
        </Helmet>
    </ChildComponent>
    

    【讨论】:

      猜你喜欢
      • 2019-01-28
      • 2016-12-10
      • 2019-04-17
      • 2019-08-03
      • 1970-01-01
      • 2021-02-25
      • 1970-01-01
      • 2019-07-08
      • 2020-08-07
      相关资源
      最近更新 更多