[英]Passing state from parent to child to child
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 .
我正在尝试将 state 从父组件传递给子组件,然后再传递给另一个子组件 function。我有一个演示可以准确解释我在这里要完成的任务。 The Map and List word/button should change the screens.
Map 和列表词/按钮应该改变屏幕。
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>
);
};
Your Slider component should use your props like this:你的 Slider 组件应该像这样使用你的道具:
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;
In Slider.js, change the button call to - onPress= {()=>props.renderMap()}在 Slider.js 中,将按钮调用更改为 - 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>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.