React根据渲染页面更改Navbar标题

  • 本文关键字:Navbar 标题 React reactjs
  • 更新时间 :
  • 英文 :


我将此BrowserRouter组件作为我的顶级组件,其状态为标题字符串。该组件呈现一个基本上是导航栏的导航程序,在那里,我想设置一个标题,该标题取决于我在网站上的位置。

该组件看起来大致喜欢

  changeTitle(title) {
    this.setState({
      title: title,
    })
  }
  <BrowserRouter>
    <div>
      <NavigationComponent title={this.state.title}/>
      <Switch>
        <Route exact path="/" render={(props) => (
          <App {...props} changeTitle= {this.changeTitle.bind(this)}/>
        )} />
        <Route exact path="/login" component={LoginComponent }/>
        <Route exact path="/logout" component={LoginComponent }/>
      </Switch>
    </div>
  </BrowserRouter>

现在,我知道如何将方法changeTitle公开到应用程序组件。但是我想进一步公开该方法,并且我实施IT的方式是ATM:

class App extends React.Component{
  constructor(props){
    super(props);
  }
  changeTitle(title) {
    this.props.changeTitle(title);
  }
  render(){
    return(
      <OverviewComponent changeTitle= {this.changeTitle.bind(this)}/>
  }
} // note: App component stripped down

在"概述"中是我真正调用Changetitle函数的第一次。

我的问题现在是:是否有一种更聪明的方法可以在不向每个孩子的方法上填写方法的情况下实施它?有更多组件在概述component之后被调用,而这些组件也需要更改标题。

在您的导航库中,我认为拥有一个事件列表时,每当您导航到另一个页面时都会检查一下。看起来您已经在使用react-router-dom,所以这是完美的。

您需要将组件与react-router-domwithRouter HOC包裹。这将使我们访问具有事件侦听器方法的history Prop。我们可以在ComponentDidMount((中创建该事件 - 列表,以便它始终活跃。

import { withRouter } from "react-router-dom"
class NavigationComponent extends React.Component{
   state = {
      title: "Home"
   }
   changeTitle = (newTitle) => {
      this.setState({
          title: newTitle
      })
   }
   componentDidMount(){
    //listens for any route changes
    this.props.history.listen(() => {
        this.changeTitle(window.location.pathname) <-- this can be whatever value you want.
    })
   }
   render(){
      <div>{this.state.title}</div>
   }
}
export default withRouter(NavigationComponent)

这似乎比必须从另一个组件传递值更直观。

检查 window.location.pathname并将路径名作为navbar标题

// Navbar.js
changeTitle = () => {
  switch(window.location.pathname){
    case '/profile':
      return 'Profile';
    case '/admin':
      return 'Admin';
    default:
      return 'Dashboard';
  }
}
render(){
 let title = changeTitle();
  return(<div>{title}</div>)
} 

最新更新