在listitem上将用户导航到New Screen,单击React native

时间:2017-06-14 07:32:14

标签: android listview react-native navigation react-router

在用户点击列表项时尝试将用户导航到下一个屏幕。我试图在这里使用Navigator,我是新手做出反应,有Redux和Flux有两种不同的架构,因为我的反应并不是很好,所以我很少混淆那里的工作。我们可以使用导航器以及使用操作来导航用户。这是我的班级: -

我得到的错误是: - undefined不是一个函数(评估' _this4.goDetailPage(rowData)')

Today.js

    import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
} from 'react-native';
import {FeedStack} from './movielistdeatilrouter';

export default class TodayView extends Component {
 constructor(props , context) {
      super(props , context);
    }
   render() {
        return (
<FeedStack />
        );
    }
 }

movielistdeatilrouter.js : -

import React from 'react';
import {StackNavigator } from 'react-navigation';
import MovieDeatilScreen from './MovieDeatilScreen';
import Movielisting from './movielisting';
export const FeedStack = StackNavigator({
  Movielisting: {
    screen: Movielisting,
    navigationOptions: {
      title: 'Movielisting',
    },
  },
  MovieDeatilScreen: {
    screen: MovieDeatilScreen,
    navigationOptions: ({ navigation }) => ({
      title: 'MovieDeatilScreen',
    }),
  },
});

movielistiing.js : -

import React, { Component } from 'react';
import { StatusBar } from 'react-native'
import { StackNavigator } from 'react-navigation';
import { NavigationActions } from 'react-navigation';
import { Actions, ActionConst } from 'react-native-router-flux';
import home  from '../images/home.png';
import MovieDeatilScreen from './MovieDeatilScreen'
const { width: viewportWidth, height: viewportHeight } = Dimensions.get('window');
import {
  StyleSheet,
  Text,
  Image,
  View,
  AsyncStorage,
  TouchableOpacity,
  TouchableHighlight,
  Dimensions,
  ListView
} from 'react-native';
const uri = 'http://csswrap.com/wp-content/uploads/2015/03/showmenu.png';
export default class Movielisting extends Component {

 constructor(props) {
     super(props);
     var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
     this.state = {
       moviesData: ds.cloneWithRows([]),
     };
   }

   componentDidMount() {
       this.fetchMoviesData();
     }
      fetchMoviesData() {
          var url = 'http://api.themoviedb.org/3/movie/now_playing?api_key=17e62b78e65bd6b35f038505c1eec409';
          fetch(url)
            .then(response => response.json())
            .then(jsonData => {
              this.setState({
                moviesData: this.state.moviesData.cloneWithRows(jsonData.results),

              });
            })
          .catch( error => console.log('Error fetching: ' + error) );
        }
  render() {
        return (
                <View style={styles.container}>

                    <ListView
                      dataSource={this.state.moviesData}
                            renderRow={this.renderRow}
                            enableEmptySections={true}
                             style={styles.ListViewcontainer}
                          />
                    </View>
        );
    }
    renderRow(rowData){
            return (
              <View style={styles.thumb} >
              <TouchableOpacity  onPress={() => this.goDeatilPage(rowData)}>
                <Image
                  source={{uri:'https://image.tmdb.org/t/p/w500_and_h281_bestv2/'+rowData.poster_path}}
                  resizeMode="cover"
                  style={styles.img} />
                  <Text style={styles.txt}>{rowData.title} (Rating: {Math.round( rowData.vote_average * 10 ) / 10})</Text>
              </TouchableOpacity>
              </View>

            );
          }
goDeatilPage = (rowData) => {
   alert('hi');
   AsyncStorage.setItem('moviesData', JSON.stringify(rowData));
       this.props.navigation.navigate('MovieDeatilScreen');
     };
}
const styles = StyleSheet.create({
  container: {
  position:'relative',
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },action: {
                                        flex: 0.4,
                                    },thumb: {
                                          backgroundColor: '#ffffff',
                                          marginBottom: 5,
                                          elevation: 1
                                        },
                                        img: {
                                          height: 300
                                        },
                                        txt: {
                                          margin: 10,
                                          fontSize: 16,
                                          textAlign: 'left'
                                        },ListViewcontainer:{
                                         marginTop:50,
                                          bottom: 50,
                                        }
});

Index.android.js : -

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  StatusBar,
  View
} from 'react-native';
import App from './app';
import DrawerMenu from './Drawer/drawer-toolbar-android';
import BookmarkView from './Pages/bookmark';
import CalendarView from './Pages/calendar';
import ClientView from './Pages/client';
import InfoView from './Pages/info';
import SettingsView from './Pages/setting';
import { DrawerNavigator, StackNavigator } from 'react-navigation';


const stackNavigator = StackNavigator({
  Info: { screen: InfoView },
  Settings: {screen: SettingsView },
  Bookmark: {screen: BookmarkView },
  Calendar: {screen: CalendarView},
  Client: {screen: ClientView},
}, {
  headerMode: 'none'
});

const easyRNRoute = DrawerNavigator({
  Home: {
    screen: App,
  },
  Stack: {
    screen: stackNavigator
  }
}, {
  contentComponent: DrawerMenu,
  contentOptions: {
    activeTintColor: '#e91e63',
    style: {
      flex: 1,
      paddingTop: 15,
    }
  }
});

AppRegistry.registerComponent('flightbot', () => easyRNRoute);

App.js类: -

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  StatusBar,
  View
} from 'react-native';
import { Navigator, NativeModules } from 'react-native';

import { COLOR, ThemeProvider } from 'react-native-material-ui';
import { Toolbar, BottomNavigation, Icon } from 'react-native-material-ui';
import Container from './Container';

import { TabRouter } from 'react-navigation';

import TodayView from './Contents/today';
import ProfileView from './Contents/profile';
import MapView from './Contents/map';
import ChatView from './Contents/chat';

const uiTheme = {
  palette: {
    primaryColor: COLOR.green500,
    accentColor: COLOR.pink500,
  },
  toolbar: {
    container: {
      height: 70,
      paddingTop: 20
    }
  }
}

const TabRoute = TabRouter({
  Today: { screen: TodayView },
  Profile: { screen: ProfileView },
  Map: { screen: MapView },
  Chat: {screen: ChatView}
  }, {
    initialRouteName: 'Today',
  }
);

class TabContentNavigator extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      active: props.value.active,
    };
  }

  //this method will not get called first time
  componentWillReceiveProps(newProps){
    this.setState({
      active: newProps.value.active,
    }); 
  }

  render() {
    const Component = TabRoute.getComponentForRouteName(this.state.active);
    return <Component/>;
  }
}

export default class App extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      active: 'Today',
    };
  }

  static navigationOptions = {
    title: 'Menu',
  };

  navigate() {
    this.props.navigation.navigate('DrawerOpen'); // open drawer
  }

  render() {
    return (
      <ThemeProvider uiTheme={uiTheme}>
        <Container>
          <StatusBar backgroundColor="rgba(0, 0, 0, 0.2)" translucent />

          <Toolbar
            leftElement="menu"
            centerElement={this.state.active}
            onLeftElementPress={() => this.navigate()}
          />

          <TabContentNavigator value={this.state} key={this.state} />

          <BottomNavigation active={this.state.active}
            hidden={false}
            style={{ container: { position: 'absolute', bottom: 0, left: 0, right: 0 } }}
          >
            <BottomNavigation.Action
              key="Today"
              icon="today"
              label="Today"
              onPress={() => this.setState({ active: 'Today' })}
            />
            <BottomNavigation.Action
              key="Profile"
              icon="person"
              label="Profile"
              onPress={() => {
                this.setState({ active: 'Profile' });
              }}
            />
            <BottomNavigation.Action
              key="Map"
              icon="map"
              label="Map"
              onPress={() => this.setState({ active: 'Map' })}
            />
            <BottomNavigation.Action
              key="Chat"
              icon="chat"
              label="Chat"
              onPress={() => this.setState({ active: 'Chat' })}
            />
          </BottomNavigation>

        </Container>
      </ThemeProvider>
    );
  }
}

我正在努力解决这个问题,今天差不多3天我正在寻找能够做到这一点的解决方案,我只是想点击列表项打开一个新的屏幕。任何人都可以告诉我该怎么做。如果有人让我知道导航到下一个屏幕的方式,我会非常感激。

我错误的ScreenShot: -

enter image description here

感谢!!!

3 个答案:

答案 0 :(得分:1)

使用“React Navigation”可以帮助您完成这项工作。

有关详细信息,请在此处找到:https://reactnavigation.org

干杯,

======更新======

我相信您设置今日组件的方式不正确,而且您的问题也不清楚,我花了一些时间来了解您想要做什么。

无论如何,如果要从中打开详细信息屏幕,今天组件应该是StackNavigator,它将控制2个屏幕(ListScreen和DetailScreen):

const TodayView = StackNavigator({
  List: {
    screen: ListScreen,
  },
  Detail: {
    screen: DetailScreen,
  },
});

然后像这样设置你的屏幕:

class ListScreen extends Component {
  static navigationOptions = {
    title: 'List',
  }

  constructor(props , context) {
    super(props , context);
    this.goToDetailScreen = this.goToDetailScreen.bind(this);
  }

  goToDetailScreen() {
    this.props.navigation.navigate('Detail');
  }

  render() {
    return (
      <TouchableOpacity onPress={() => this.goToDetailScreen()}>
        <Text>GO TO DETAIL</Text>
      </TouchableOpacity>
    );
  }
}

class DetailScreen extends Component {
  static navigationOptions = {
    title: 'Detail',
  }

  render() {
    return (
      <TouchableOpacity onPress={() => this.props.navigation.goBack()}>
        <Text>BACK TO LIST SCREEN</Text>
      </TouchableOpacity>
    );
  }
}

在他们的Github回购中有一个叫做“StacksInTabs”的例子,你可能想看看它:https://github.com/react-community/react-navigation/blob/master/examples/NavigationPlayground/js/StacksInTabs.js

干杯,

答案 1 :(得分:0)

最后它起作用了,这就是我如何跟踪代码中的变化。 : -

<View style={styles.container}>
                    <ListView
                      dataSource={this.state.moviesData}
                            renderRow={this.renderRow.bind(this)}
                            enableEmptySections={true}
                             style={styles.ListViewcontainer}
                          />
                    </View>

我刚刚将.bind(this)函数添加到renderRow。

休息是相同的: -

renderRow(rowData){
            return (
              <View style={styles.thumb} >
              <TouchableOpacity  onPress={()=>this.goDeatilPage(rowData)}>
                <Image
                  source={{uri:'https://image.tmdb.org/t/p/w500_and_h281_bestv2/'+rowData.poster_path}}
                  resizeMode="cover"
                  style={styles.img} />
                  <Text style={styles.txt}>{rowData.title} (Rating: {Math.round( rowData.vote_average * 10 ) / 10})</Text>
              </TouchableOpacity>
              </View>

            );
          }
goDeatilPage = (rowData) => {
   alert('hi');
   AsyncStorage.setItem('moviesData', JSON.stringify(rowData));
       this.props.navigation.navigate('MovieDeatilScreen');
     }

感谢@Goon为您的时间我非常感谢您的努力。谢谢兄弟。

答案 2 :(得分:0)

使用React Navigation进行导航屏幕,它非常易于使用,

  • 以反复原生
  • 创建3个类
  
      
  1. 定义了导航器类   2.第一个屏幕   3.navigate screen
  2.   

1.Basic.js

    import {
  StackNavigator,
} from 'react-navigation';

const BasicApp = StackNavigator({
  Main: {screen: Movielistiing},
  Detail: {screen: Movielistdeatilrouter},
});
module.exports = BasicApp;

2.Movielistiing.js

class Movielistiing extends React.Component {
  static navigationOptions = {
    title: 'Welcome',
  };
  render() {
    const { navigate } = this.props.navigation;
    return (
      <Button
        title="Go to movie detail"
        onPress={() =>
          navigate('Detail', { name: 'Jane' })
        }
      />
    );
  }
}

3.Movielistdeatilrouter.js

class Movielistdeatilrouter extends React.Component {
  static navigationOptions = ({navigation}) => ({
    title: navigation.state.params.name,
  });
  render() {
    const { goBack } = this.props.navigation;
    return (
      <Button
        title="Go back"
        onPress={() => goBack()}
      />
    );
  }
}