Estoy tratando de generar una tarjeta a partir de datos JSON usando la función Map en React Native.
Quiero poder navegar a otra página haciendo clic en esta tarjeta.
Esta es la solución que estoy intentando:
function display() { return restaurant.map((item) => { return( <TouchableHighlight onPress={() => this.props.navigation.navigate('Restaurant')}> <View style={styles.card}> <View style={styles.cardHeadText}> <Text style={styles.title}> { item.name } </Text> <Text> { item.type } </Text> </View> </View> </TouchableHighlight> ); }); } class RestaurantCard extends Component { render() { return ( <View style={styles.container}> {display()} </View> ); } }Pero me sale el siguiente error:
Undefined no es un objeto (evaluando '_this.props.navigation')
¿Qué estoy haciendo mal?
Puede pasar this como argumento a la función de map como se describe en la documentación: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
function display() { return restaurant.map((item) => { return( <TouchableHighlight onPress={() => this.props.navigation.navigate('Restaurant')}> <View style={styles.card}> <View style={styles.cardHeadText}> <Text style={styles.title}> { item.name } </Text> <Text> { item.type } </Text> </View> </View> </TouchableHighlight> ); }, this); // over here }Puedes probarlo :) He pasado la navegación como accesorios en la función de visualización, destruyéndola y reutilizándola como un atajo para acceder a this.props.navigation..
Extraer la lógica del clic en un handler facilitó la lectura y el control, puede agregar verificaciones y otras cosas mucho más fáciles.
function display(props) { const { navigation } = props const handlerClick = (item) => { /* all the content of item (name, and type) will be passed in props of the other page component */ navigation.navigate("Restaurant", { ...item}) } return restaurant.map((item) => { return( <TouchableHighlight onPress={() => handlerClick(item)}> <View style={styles.card}> <View style={styles.cardHeadText}> <Text style={styles.title}> { item.name } </Text> <Text> { item.type } </Text> </View> </View> </TouchableHighlight> ); }); } class RestaurantCard extends Component { render() { return ( <View style={styles.container}> {display(this.props.navigation)} </View> ); } }