首页 > 解决方案 > 如何递归调用组件并跟踪 React Native 中的嵌套级别

问题描述

我有一个名为“ CommentList ”和“ Comment ”的组件。CommentList 通过使用地图调用“评论”来呈现评论(例如循环运行 10 次)。

现在,如果您点击任何列出的评论,“评论”可以再次使用一组新的道具呈现“评论列表”。所以,它就像一个嵌套的东西。对于每个更深层次,我都有缩进。就像你点击第一个评论一样,它会调用“CommentList”并列出它自己的 10 条评论,并带有一些缩进等等。

如果用户深度为 5 级,我想跟踪嵌套级别并完全清除列表,并从屏幕上的第 6 级重新开始相同的行为。

我还想在新屏幕上有一个后退按钮,一旦我们进入新屏幕(6 到 10),就可以回到第一组(1 到 5)

我将只使用功能组件。我应该如何解决这个问题,一旦我有一些想法来实现它,我将包含代码。任何想法都会有所帮助。

标签: javascriptreactjstypescriptreact-nativerecursion

解决方案


以下是让您开始使用递归方法的基本思想。这是评论的根容器。

import React, { Component } from "react";
import { View, Text } from "react-native";
import CommentsList from "./CommentsList";
class App extends Component {
  constructor() {
    super();
    this.state = {
      currentLevel: 0,
      comments: [
        {
          level: 0,
          comment: {
            text: "level 0 and comment one",
            comments: [
              {
                level: 1,
                comment: {
                  text: "level 1 and comment one",
                  comments: []
                }
              },
              {
                level: 1,
                comment: {
                  text: "level 1 and comment two",
                  comments: []
                }
              },
              {
                level: 1,
                comment: {
                  text: "level 1 and comment three",
                  comments: []
                }
              }
            ]
          }
        },
        {
          level: 0,
          comment: {
            text: "level 0 and comment two",
            comments: []
          }
        },
        {
          level: 0,
          comment: {
            text: "level 0 and comment three",
            comments: []
          }
        }
      ]
    };
  }
  render() {
    return (
      <View style={{ flex: 1, justifyContent: "center", marginTop: 100 }}>
        <Text>This is the rootview</Text>
        <CommentsList comments={this.state.comments} />
      </View>
    );
  }
}

export default App;

以下是您的 CommentsList 组件。

import React from "react";
import { View, FlatList } from "react-native";
import Comment from "./Comment";

const CommentsList = props => {
  return (
    <View style={{ flex: 1, justifyContent: "center" }}>
      <FlatList
        data={props.comments}
        renderItem={({ item, index }) => {
          return <Comment comment={item.comment} level={item.level} />;
        }}
      />
    </View>
  );
};

export default CommentsList;

以下是您的评论组件。因为它是递归的,它将包含 CommentsList 组件。


import React from "react";
import { View, Text } from "react-native";
import CommentsList from "./CommentsList";
const Comment = props => {
  return (
    <View style={{ flex: 1, justifyContent: "center" }}>
      <Text>
        {props.comment.text} + {props.level}
      </Text>
      <CommentsList comments={props.comment.comments} />
    </View>
  );
};

export default Comment;


推荐阅读