将屏幕从FlatList的项目更改为该项目的问题屏幕

时间:2020-10-22 15:54:00

标签: react-native

我在使用本机的英语应用程序。我用这样的类别和child_category创建了一个主页 enter image description here。当我单击类别时,它将显示该类别的child_category。我做得很好但是,现在我尝试单击child_category,它将变为一个类似enter image description here的问题屏幕。我尝试使用OnPress,但无法正常工作。有什么办法吗?这是我的代码。

这是Navigator.js

const Stack = createStackNavigator();

const AppNavigator = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Start">
        <Stack.Screen
          name="Start"
          component={Start}
          options={{
            headerShown: false,
            title: 'Homepage',
            headerStyle: {
              backgroundColor: '#fff',
            },
            headerTitleStyle: {
              fontWeight: 'bold',
            },
            headerTitleAlign: 'center', // căn giữa stack navigator header
          }}
        />
        <Stack.Screen
          name="Login"
          component={Login}
          options={{
            title: 'Đăng nhập',
            headerStyle: {
              backgroundColor: '#fff',
            },
            headerTitleStyle: {
              fontWeight: 'bold',
            },
            headerTitleAlign: 'center',
          }}
        />
        <Stack.Screen
          name="Signup"
          component={Signup}
          options={{
            title: 'Đăng ký',
            headerStyle: {
              backgroundColor: '#fff',
            },
            headerTitleStyle: {
              fontWeight: 'bold',
            },
            headerTitleAlign: 'center',
          }}
        />
        <Stack.Screen
          name="ChangePass"
          component={ChangePass}
          options={{
            title: 'Cập nhật mật khẩu',
            headerStyle: {
              backgroundColor: '#fff',
            },
            headerTitleStyle: {
              fontWeight: 'bold',
            },
            headerTitleAlign: 'center',
          }}
        />
        <Stack.Screen
          name="EditProfile"
          component={EditProfile}
          options={{
            title: 'Cập nhật thông tin tài khoản',
            headerStyle: {
              backgroundColor: '#fff',
            },
            headerTitleStyle: {
              fontWeight: 'bold',
            },
            headerTitleAlign: 'center',
          }}
        />
        <Stack.Screen
          name="Home"
          component={TabSrceen}
          options={{
            headerShown: false,
            title: 'Welcome to MyEnglish',
            headerStyle: {
              backgroundColor: '#fff',
            },
            headerTitleStyle: {
              fontWeight: 'bold',
              alignSelf: 'center',
            },
          }}
        />

        <Stack.Screen
          name="ChildCategoryItem"
          component={ChildCategoryItem}
          options={{
            headerStyle: {
              backgroundColor: '#fff',
            },
            headerTitleStyle: {
              fontWeight: 'bold',
              alignSelf: 'center',
            },
          }}
        />

        <Stack.Screen
          name="Quiz"
          component={Quiz}
          options={{
            headerStyle: {
              backgroundColor: '#fff',
            },
            headerTitleStyle: {
              fontWeight: 'bold',
              alignSelf: 'center',
            },
          }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
};
export default AppNavigator;

这是我的Home.js。我在此使用ChildCategory.js

const Home = () => {
  //render chủ đề con
  const renderChildCategoryItem = ({item}) => {
    return (
      <ChildCaterogyItem
        // CategoryName={data.find((x) => x.id == idSelected)}
        data_child={item}
      />
    );
  };

  //render chủ đề chính
  const renderCategoryItem = (item) => {
    return (
      <CategoryItem
        onSelected={onSelected}
        selected={item.id == idSelected}
        {...item}
        data={item}
      />
    );
  };

  const [data_child, setData_child] = useState([]);
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [idSelected, setIdSelected] = useState(1);

  const onSelected = (id) => {
    setIdSelected(id);
  };

  useEffect(() => {
    _fetchAllCategory();
    _fetchListChildCategory();
  }, [idSelected]);

  //fetch data chủ đề
  const _fetchAllCategory = async () => {
    try {
      const res = await fetch('http://192.168.1.4:8080/api/category', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });
      const data = await res.json();
      if (data.status == 200) {
        setData(data.data);
      }
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
    }
  };

  //fetch data chủ đề con
  const _fetchListChildCategory = async () => {
    try {
      setLoading(true);
      const res = await fetch(
        'http://192.168.1.4:8080/api/childcategory/' + idSelected,
        {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          },
        },
      );
      const data = await res.json();
      if (data.status == 200) {
        setData_child(data.data);
      }
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <StatusBar barStyle="light-content" />
      <SafeAreaView style={styles.container}>
        <ScrollView style={styles.wrap} showsVerticalScrollIndicator={false}>
          <View style={styles.header}>
            <View style={styles.headerTitle}>
              <Text style={styles.heading}>
                An English learning app to improve your English vocabulary
              </Text>
            </View>
          </View>

          <View style={styles.listCategoryItem}>
            {data.map(renderCategoryItem)}
          </View>

          <View style={styles.listChildCategory}>
            <Text style={styles.listChildCategoryText}>
              Some categories for you
            </Text>

            <View style={styles.listCategory}>
              <FlatList
                data={data_child}
                // extraData={data_child}
                // keyExtractor ={(item)=> item.id}
                renderItem={renderChildCategoryItem}
              />
              
              {loading && (
                <View style={styles.loading}>
                  <ActivityIndicator size="large" color="#F1CB7A" />
                </View>
              )}
            </View>
          </View>
        </ScrollView>
      </SafeAreaView>
    </>
  );
};

这是我的ChildCategoryItem.js`

const ChildCategoryItem = ({data_child}, props) => {
  return (
    <TouchableOpacity
      style={styles.container}
      // onPress={() => this.props.navigation.navigate('Quiz',{id: item.id}) }
      // onPress={() => navigation.push('Quiz',item)}
    >
      <Button
        title="Start"
        onPress={() => props.navigation.navigate('Quiz', {id: item.id})}
      />
      <View>
        <Image source={{uri: data_child.Image}} style={styles.image} />
      </View>
      <Text style={styles.name}>{data_child.id}</Text>
      <Text style={styles.description}>{data_child.Description}</Text>
      <View style={styles.smileList}>
        <Image
          source={require('../assets/images/smile.png')}
          style={styles.icon}
        />
        <Text style={styles.smile}>{data_child.smile || 0}%</Text>
      </View>
    </TouchableOpacity>
  );
};

这是我的Quiz.js

    export default class Questions extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      questions: [],
      current: 0,
      correctScore: 5,
      totalScore: 50,
      data: {
        score: 0,
        correctAnswers: 0
      },
      completed: false
    };
  }

  
  fetchQuestions = async () => {
    const {params} = this.props.navigation.state;
    await this.setState({ loading: true });
    const response = await fetch(
      `http://192.168.1.4:8080/api/question/`, + params.id,
      // + params,
      {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          },
        },
    );
    const questions = await response.json();

    const { data } = questions;

    data.forEach(item => {
      item.id = Math.floor(Math.random() * 10000);
    });

    await this.setState({ questions: data, loading: false });
  };

1 个答案:

答案 0 :(得分:0)

您是否尝试过在控制台上记录日志,以查看它是否被调用?我认为这可能是样式/方法问题,因为您试图将整个组件包装成可触摸的不透明度。尝试将可触摸的不透明度更改为视图,然后单击按钮导航到屏幕。

如果这不起作用,则您的导航功能可能没有通过道具传递下来。另外,还要确保您是从react-native而不是从react-native-gesture-handler导入的TouchableOpacity。

编辑:看来您的按钮使用的是“ props”,但是包装器使用的是“ this.props”,您应该使用“ props”,因为它是通过功能组件而不是基于类的组件传递的。