我在react native中实现了grid view
。它从json获取数据并显示。
现在,我想点击grid item
并根据grid
的当前位置数据显示内容。
答案 0 :(得分:2)
您可以将任何Touchable组件与onPress
处理程序一起使用。
您可以将导航器作为道具传递,如以下示例的renderScene
部分所示。
<强> index.ios.js 强>
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
View,
TouchableHighlight,
Navigator
} from 'react-native';
import GridView from 'react-native-grid-view';
import Movie from './Movie.js';
import MovieDetail from './MovieDetail.js';
class ReactNativeGridViewTest extends Component {
constructor(props) {
super(props);
this.state = {
movies: ['hello', 'blabla', 'BatMan', 'SuperMan']
};
}
onHandleItemPress(item){
this.refs.navigator.push({
id: 'detail',
data:item
});
}
renderItem(item) {
return (
<TouchableHighlight onPress={this.onHandleItemPress.bind(this, item)}>
<View>
<Movie item={item}/>
</View>
</TouchableHighlight>
);
}
renderScene(route,navigator){
switch(route.id){
case 'master': return (
<View style={styles.container}>
<GridView
items={this.state.movies}
itemsPerRow={3}
renderItem={this.renderItem.bind(this)}
/>
</View>
)
case 'detail': return (<MovieDetail navigator={navigator} data={route.data}/>)
}
}
render() {
return (
<Navigator ref="navigator"
initialRoute={{id: 'master'}}renderScene={this.renderScene.bind(this)}/>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('ReactNativeGridViewTest', () => ReactNativeGridViewTest);
<强> Movie.js 强>
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
View,
TouchableHighlight,
} from 'react-native';
export default class Movie extends Component{
render(){
return (
<View style={{width:40, height:40, margin: 20, backgroundColor:'red'}}>
<Text>{this.props.item}</Text>
</View>
)
}
}
<强> MovieDetail.js 强>
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
View,
TouchableHighlight,
} from 'react-native';
export default class MovieDetail extends Component{
render() {
return (
<View style={styles.container}>
<TouchableHighlight onPress={()=> this.props.navigator.pop()}>
<Text>Go Back </Text>
</TouchableHighlight>
<View style={{width:40, height:40, margin: 20, backgroundColor:'red'}}>
<Text>{this.props.data}</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
您还可以查看working example on Github。