I know I am close to getting this to work but something is off. I am trying to pass a state from a parent component to a child and then to another child function. I have a demo that explains exactly what I am trying to accomplish here. The Map and List word/button should change the screens.
I will also give the code below but I recommend the working demo above.
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>
);
};
CodePudding user response:
Your Slider component should use your props like this:
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;
CodePudding user response:
In Slider.js, change the button call to - 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>
);
};