react-native - 如何访问无法访问 this.props.navigation 的功能组件或类组件内部的 react 导航?

标签 react-native react-navigation expo

我在使用 expo 的 react native 平台中执行此操作。

我想显示项目列表( ListItems.js) All_Employees_screen.js 。这些项目是通过功能组件呈现的,我想要一个 onRowPress() 处理程序,以便在单击它时我可以将其导航到另一个 View ,但我不知道如何在 react-navigation 上执行此操作?

或者因为新的功能组件可以是一个类组件(这会更好)我如何访问其中的导航内容?

enter image description here

AllProperties.js

import _ from 'lodash';
import React, {
  Component
} from 'react';

import {
  Button,
  ListView,
  ScrollView
} from 'react-native';


import ListItem from './ListItem';
import { connect } from 'react-redux';
import { propertiesFetch } from '../../actions';

// import { FormLabel, FormInput } from 'react-native-elements'

class AllPropertiesScreen extends React.Component {

  componentWillMount(){
    this.props.propertiesFetch();
    this.createDataSource(this.props);
  }

// we do this componentWillMount & componentWillReceiveProps (nextProps) thing twice, coz once the component is
// loaded it loads all teh values but when user hits another view like Create property, The Property data still exists
// in the global state object,

// we could move all the  dc dataSource code into componentWillReceiveProps but its actually gonna benefit us
 // if we make sure that we try to build our data source both when the component first loads up
// & when second time  after we go back and forth other compoennts.

  componentWillReceiveProps(nextProps){
    // nextProps are the next set of props that this component will be rendered with
    // this.props is still the old set of props
    this.createDataSource(nextProps);
  }


createDataSource({ properties }){
  const ds = new ListView.DataSource({
        rowHasChanged: (r1, r2) => r1 !== r2
      });
      this.dataSource = ds.cloneWithRows(properties);
}


    static navigationOptions = ({ navigation }) => {
      const {state, setParams} = navigation;
      return {
        title: 'All Emplooyee',
        headerRight: (
          <Button
            title='Add'
            // onPress={() => setParams({ mode: isInfo ? 'none' : 'info'})}
             onPress={() => navigation.navigate('createProperty')
             }
          />
        ),
      };
    };

goBack(){
    console.log('65 - go Back clicked');
}

renderRow(property){
  // console.log('67-AllPropertiesScreen  =', property);
  return <ListItem property={property}
      onPress={() => { console.log('65 - go Back clicked')  }}
    />;
}

  render() {
    console.log('72-AllPropertiesScreen  this.props', this.props );
    return(
        <ListView
          enableEmptySections
          dataSource={this.dataSource}
          renderRow={this.renderRow}
        />
    );
  }
}

const mapStateToProps = state => {
  console.log('83 - AllPropertiesScreen  state. properties', state );
  const properties = _.map(state.properties, (val, uid ) => {
      return { ...val, uid };  //   { shift: 'Monday'}
  });

  return { properties };
};

export default connect(mapStateToProps, {propertiesFetch}) (AllPropertiesScreen);

列表项.js
import React, { Component } from 'react';
import { Text, TouchableWithoutFeedback, View } from 'react-native';

class ListItem extends Component {

  // onRowPress(){
  //   Actions.employeeEdit({ employee: this.props.employee });
  // }

  render(){
    const { agent_name, cell, address } = this.props.property;
    console.log('14- ListItem ', this.props);

    return (
        <View>
          <CardSection>
            <Text style={styles.titleStyle}>
                name
            </Text>
            <Text style={styles.titleStyle}>
              cell
            </Text>
            <Text style={styles.titleStyle}>
              address
            </Text>
          </CardSection>
      </View>
    );
  }
}

const styles = {
  titleStyle: {
    fontSize: 18,
    paddingLeft: 15
  }
}

export default ListItem;

//

main.js(这是我连接所有导航路径的地方。
class App extends React.Component {
  render() {
    const MainNavigator = TabNavigator({
          // auth: { screen : AuthScreen },
          // review: { screen: ReviewScreen },  
          // signup: { screen : SignupScreen }, 
          followup: { screen: FollowupScreen },               welcome: { screen : WelcomeScreen },
          auth: { screen : AuthScreen },
          signup: { screen : SignupScreen },
          main: {
            screen: TabNavigator ({
              followup: { screen: FollowupScreen },
              map: { screen: MapScreen },
              deck: { screen: DeckScreen },
              settings : {
                screen: StackNavigator ({
                  settings: { screen: SettingsScreen },
                  // settings: { screen: SettingsScreen },
                  UserProfile: { screen: UserProfileScreen },
                  HelpSupport: { screen: HelpSupportScreen },
                  Notifications: { screen: NotificationsScreen },
                  Signout: { screen: SignoutScreen }   // not working, Navigation object not accessible inside the component
                })  //screen: StackNavigator ({
              },
              followup : {
                screen: StackNavigator ({
                  followup: { screen: FollowupScreen },
                  allProperties: { screen: AllPropertiesScreen },
                  createProperty: { screen: PropertyCreateScreen },
                  Red: { screen: RedPriorityScreen },   // not working, Navigation object not accessible inside the component
                  GreyPriority: { screen: GreyPriorityScreen },

                })  //screen: StackNavigator ({
              },
              draw: {
                screen: DrawerNavigator ({
                  drawin: { screen: DrawScreen },
                })  //screen: StackNavigator ({
              }
            }) //screen: TabNavigator
          }
    }, {
      navigationOptions: {
          tabBarVisible: false
      },
      lazy: true
});

return (
  <Provider store={store}>
    <View style={styles.container}>
      <MainNavigator />
    </View>
  </Provider>
);
}
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    // alignItems: 'center',
    justifyContent: 'center',
  },
});

Expo.registerRootComponent(App);

@Matt 建议的解决方案,但只要我放置了 navigation={this.props.navigation} 它就会提示。 undefined 不是一个对象(评估 this.props.navigation )
renderRow(property){
  return (
    <ListItem
      property={property}
      navigation={this.props.navigation}
      onPress={() => {
        console.log( '70-on Press  inside renderRow ');
      }}/>
  );
}

最佳答案

如果组件不是屏幕,则必须导入导航。

尝试这个:

import React from 'react';
import { Button } 'react-native';
import { withNavigation } from 'react-navigation';

class MyBackButton extends React.Component {
  render() {
    return <Button title="Back" onPress={() => { this.props.navigation.goBack() }} />;
  }
}

// withNavigation returns a component that wraps MyBackButton and passes in the
// navigation prop
export default withNavigation(MyBackButton);

欲了解更多信息,请查看
https://reactnavigation.org/docs/connecting-navigation-prop.html

关于react-native - 如何访问无法访问 this.props.navigation 的功能组件或类组件内部的 react 导航?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45022925/

相关文章:

objective-c - 如何将数据从 native react 传递到 native iOS View ?

react-native - react native 路由器通量不显示屏幕

react-native - 在react-navigation v5中处理路由名称的最佳实践

react-native - React Native - 命令 PhaseScriptExecution 失败,退出代码非零

react-native - undefined 不是对象(评估 'object.keys(routeConfigs)' )

javascript - 从 Tab Navigator Tab Press 触发类函数调用 - React Native/Navigation

react-native - 使用 AsyncStorage 保存列表

javascript - 使用 React Navigation 进行左右导航

javascript - React Navigation 从自定义标题中的按钮导航到新屏幕

javascript - 类型错误 : TypeError: null is not an object (evaluating 'this.state.email' )