在HOC中包装时访问反应导航道具(绑定它)?

问题描述 投票:0回答:1

我对React Native,React Navigation和HOC很新。我正在尝试使用react-native-responsive-ui HOC和react-navigation。对于普通组件,我可以这样做:

export default class SettingsScreen extends React.Component {
  static navigationOptions = {
    title: 'Settings',
    headerRight: <Button onPress={() => props.navigation.navigate('SettingsScreen')} title="Btn" />
  }
  ...
}

但是,我发现,如果我用responsive HOC包装我的组件,在我的组件中定义navigationOptions没有任何效果。我必须在包装的组件上定义它们:

class HomeScreen extends React.Component { ... }

const ResponsiveHomeScreen = responsive(HomeScreen)
ResponsiveHomeScreen.navigationOptions = {
  title: 'Home',
  headerRight: <Button onPress={() => this.props.navigation.navigate('SettingsScreen')} title="Btn" />
}
export default ResponsiveHomeScreen

这样可以正常显示所有内容,但单击按钮会崩溃:

undefined is not an object (evaluating '_this3.props.navigation')

显然,“this”不受我包装组件的约束。我只是不确定如何限制它,或者如果我接近这个错误,还有另一种方法,我错过了。思考?

javascript react-native react-navigation
1个回答
0
投票

Li357的评论有解决方案。根据navigationOptions,我只是将the docs重写为函数:

const ResponsiveHomeScreen = responsive(HomeScreen)
ResponsiveHomeScreen.navigationOptions = ({navigation}) => {
  return {
    title: 'FlashNote',
    headerRight: <Button onPress={() => navigation.navigate('SettingsScreen')} title="Btn" />
  }
}

瞧,问题解决了。谢谢,Li357!

© www.soinside.com 2019 - 2024. All rights reserved.