将状态从 parent 传递到 child 再到 child

Passing state from parent to child to child

我知道我快要让它工作了,但有些地方不对劲。我正在尝试将状态从 parent 组件传递到 child,然后传递到另一个 child 函数。我有一个演示,可以准确解释我要完成的任务 here。地图和列表 word/button 应该改变屏幕。

我也会给出下面的代码,但我推荐上面的工作演示。

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>
  );
};

你的 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;

在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>
  );
};