通过React Navigation从任何组件访问导航道具

时间:2018-08-20 21:20:59

标签: react-native react-navigation

我有3个js文件,2页(HomePageSecondPage)和1页(添加到ComponentBlock的{​​{1}})。
如何从HomePage导航到ComponentBlock? 我的意思是,当我直接在HomePage中使用onPress Button时,一切都很好,我可以从主页导航到第二,然后导航到主页,但是我无法从主页中添加的ComponentBlock导航到第二。

首页:

SecondPage

第二页:

import {createStackNavigator} from 'react-navigation';
import Second from './8-SecondPage'
import ComponentBlock from './8-Component-Block';

class Home extends React.Component {
  render() {
    return (
      <ComponentBlock />
    );
  }
}

const App = createStackNavigator(
  {
    Home: {screen: Home},
    Second: {screen: Second},
    Third: {screen: ComponentBlock},
  },
);

export default App;

ComponentBlock:

export default class Second extends Component {
  render() {
    return (
      <View>
        <TouchableOpacity
          onPress={() => this.props.navigation.navigate('Home')}
        >
          <Text>Go to Home Page</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

1 个答案:

答案 0 :(得分:2)

在BlockComponent文件中

import { withNavigation} from 'react-navigation';
export default withNavigation(BlockComponent);

您现在可以使用

this.props.navigation.navigate('SecondPage');