Sé que estoy cerca de hacer que esto funcione, pero algo está mal. Estoy tratando de pasar un estado de un componente principal a un elemento secundario y luego a otra función secundaria. Tengo una demostración que explica exactamente lo que estoy tratando de lograr aquí . La palabra/botón Mapa y Lista debería cambiar las pantallas.
También daré el código a continuación, pero recomiendo la demostración de trabajo anterior.
export default class App extends React.Component { constructor(props) { super(props); this.state = { whichComponentToShow: "Screen1" }; } goToMap = () => { this.setState({ whichComponentToShow: "Screen2" }); }; goToList = () => { this.setState({ whichComponentToShow: "Screen1" }); }; render() { const { whichComponentToShow } = this.state; return ( <View style={{padding: 40,backgroundColor: whichComponentToShow === "Screen1" ? "aquamarine" : "aqua", flex: 1}}> <Text style={{fontSize: 20}}> Home - Class Component - {this.state.whichComponentToShow} </Text> <ListHome renderMap={this.goToMap} renderList={this.goToList}/> </View> export default class ListHome extends React.Component { render() { return ( <View style={{ backgroundColor: "#ddd", padding: 10 }}> <Text>ListHome</Text> <Slider renderMap={this.props.renderMap} renderList={this.props.renderList} /> </View> const Slider = (props) => { return ( <View style={{ backgroundColor: "#ccc", flex: 1 }}> <Text>Slider</Text> <TouchableOpacity onPress={() => {props.renderMap; }}> <Text> Map </Text> </TouchableOpacity> <TouchableOpacity onPress={() => {props.renderList; }}> <Text> List </Text> </TouchableOpacity> </View> ); };Su componente Slider debería usar sus accesorios de esta manera:
import * as React from 'react'; import { Text, View, StyleSheet, Button, TouchableOpacity} from 'react-native'; const Slider = (props) => { return ( <View style={{ backgroundColor: "#ccc", flex: 1 }}> <Text>Slider</Text> <TouchableOpacity onPress={props.renderMap}> <Text> Map </Text> </TouchableOpacity> <TouchableOpacity onPress={props.renderList}> <Text> List </Text> </TouchableOpacity> </View> ); }; export default Slider;En Slider.js, cambie la llamada del botón a - onPress= {()=>props.renderMap()}
const Slider = (props) => { return ( <View style={{ backgroundColor: "#ccc", flex: 1 }}> <Text>Slider</Text> <TouchableOpacity onPress={() =>props.renderMap()}> <Text> Map </Text> </TouchableOpacity> <TouchableOpacity onPress={() => props.renderList()}> <Text> List </Text> </TouchableOpacity> </View> ); };