我有一个具有顶级 <App />
的 React 应用程序组件(从 create-react-app 开始构建)。我的顶级组件看起来像这样:
<Header title={this.state.appTitle} theme={this.state.theme} />
<Switch>
{routes.map((route, index) => <Route key={index} {...route} />)}
<Route component={NotFound} />
</Switch>
(routes
是一个 {component:, to: } 对象的数组)。 <Route>
渲染的每个组件使用一个名为 <Page>
的子组件我在其中设置标题并包装一些内容:
<Page title="About Us">
<p>Content here</p>
</Page>
有时页面可能会使用不同的主题,我想将其应用到 <Header />
当查看该页面时:
<Page title="About Us" theme="alt">
我要做的是改变 appTitle
和 theme
状态 <App />
渲染每个组件时。做这个的最好方式是什么?使用 React 的生命周期钩子(Hook)之一?其他一些改变“顶级”状态的方法?我如何通过 react-router <Route>
将操作传递给这些组件?如果是的话?
最佳答案
您可以将函数传递给每个组件,并在每个子组件挂载时调用该函数,使用 componentDidMount生命周期方法。
<Switch>
{routes.map((route, index) => {
const Comp = route.component;
return <Route
key={index}
{ ...route}
// overwrite the component prop with another component
component={
(routeProps) => (
<Comp
{...routeProps}
childHasMounted={() => this.setState({ name: route.name })}
/>
)
}
/>
})}
<Route component={NotFound} />
</Switch>
// child.js
class Child extends React.Component {
componentDidMount() {
this.props.childHasMounted();
}
}
关于javascript - 基于子组件在 <App/> 级别更改 React 状态的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48104321/