gpt4 book ai didi

javascript - 选择 react 路由器时的setState( react )

转载 作者:行者123 更新时间:2023-11-30 20:03:28 27 4
gpt4 key购买 nike

我在 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>
);
}
}

最佳答案

您可以像这样在使用 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>
);
}
}

关于javascript - 选择 react 路由器时的setState( react ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53144582/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com