选择反应路由器时的setState(反应)

时间:2018-11-04 19:30:41

标签: javascript reactjs react-router

我在react框架中创建一个Web应用程序。输入适当的路由器时,我试图将状态更改为文本。如何编写它才能使其正常工作?

class Header extends React.Component {
  state = {
    title: ""
  };

  render() {
    const { title } = this.state;

    return (
      <div>
        <Typography variant="h6" color="inherit" noWrap>
          {title}
        </Typography>
        <Switch>
          <Route exact path="/" component={HomePage} title="Dashboard" />
          <Route path="/payment" component={FeaturePage} title="Payment" />
          <Route path="" component={NotFoundPage} />
        </Switch>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

您可以像这样继续使用React路由器,将更新功能传递给组件。

class Header extends React.Component {
state = {
    title: ""
};

updateTitle(newTitle){
    this.setState({title: newTitle})
}

render() {
const { title } = this.state;

return (
  <div>
    <Typography variant="h6" color="inherit" noWrap>
      {title}
    </Typography>
    <Switch>
      <Route exact path="/" render={()=> <HomePage updateTitle={this.updateTitle}/>} title="Dashboard" />
      <Route path="/payment" render={()=> <FeaturePage updateTitle={this.updateTitle}/>} title="Payment" />
      <Route path="" component={NotFoundPage} />
    </Switch>
  </div>
);
}
}