隐式传递路由器历史

Implicitly passing router history

我正在制作一个带有 react-router 的网络应用程序,它的导航类似于移动堆栈导航。页面内容应该包装在 NavigationScreen 对象(控制侧边栏、导航栏和作品)中:

class HomeScreen extends React.Component {
  render() {
    return (
       <NavigationScreen>
         <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
           <Text>Home Screen</Text>
           <Link to='/details'>details</Link>
        </View>
       </NavigationScreen>
    );
  }
}

路线是这样的:

export default class App extends React.Component {
  render() {
    return (
      <BrowserRouter>
        <View style={{ position: 'absolute', top: 0, bottom: 0, left: 0, right: 0 }}>
          <Route exact path='/' component={HomeScreen} />
          <Route path='/details' component={DetailsScreen} />
        </View>
      </BrowserRouter>
    );
  }
}

但我想我在计划中犯了一个错误。我希望导航栏有一个 "back button",它应该通过调用 this.props.history.goBack 来工作。问题是 HomeScreen class 收到了这个道具,而不是 NavigationScreen。我能看到的唯一解决方案是制作一个相当尴尬的道具传递:

class HomeScreen extends React.Component {
  render() {
    return (
       <NavigationScreen history=this.props.history>
         <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
           <Text>Home Screen</Text>
           <Link to='/details'>details</Link>
        </View>
       </NavigationScreen>
    );
  }
}

IMO 看起来很糟糕,有没有更好的方法?

如果您不想将 history 作为 prop 传递,您可能想在 NavigationScreen 上使用 withRouter HOC。