javascript - 基于子组件在 <App/> 级别更改 React 状态的最佳方法

标签 javascript reactjs react-router react-router-v4 react-component

我有一个具有顶级 <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">

我要做的是改变 appTitletheme状态 <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/

相关文章:

javascript - 测试 Angular $emit 和 $on 事件

reactjs - defaultValue 或值不适用于 FormItem ANTD

javascript - 使用 uniqid 生成两次唯一 ID

wordpress - 使用 WordPress 响应 Router v4 和 htaccess

javascript - 如何使用 jquery $this 从列表中删除特定对象?

javascript - jquery deferred.done : passing a data array to done method

javascript - 本地镜像未加载到 <Image> react native

react-router - react 路由器 3 : What is the effect of brackets () in a route's path definition?

reactjs - 使用 Typescript 在 React 中重定向

javascript - 在 jQuery 中获取元素的值