Ama*_*rma -2 javascript recursion typescript reactjs react-native
我有一个名为“ CommentList ”和“ Comment ”的组件。CommentList 通过使用映射调用“Comment”来呈现评论(例如循环运行 10 次)。
现在,如果您点击任何列出的评论,“评论”可以再次使用一组新的道具渲染“评论列表”。所以,它就像一个嵌套的东西。对于每个更深的级别,我都有缩进。就像如果你点击第一个评论,它会调用“CommentList”并列出自己的 10 条评论,并带有一些缩进等等。
我想跟踪嵌套级别,并在用户深度为 5 级时完全清除列表,并从屏幕上的第 6 级开始新的相同行为。
我还想在新屏幕上有一个后退按钮,以便在我们进入具有新组(6 到 10)的新屏幕时返回到第一个组(1 到 5)
我将只使用功能组件。我应该如何解决这个问题,一旦我有了一些想法来实现这个问题,我将包含代码。任何想法都会有所帮助。
以下是帮助您开始使用递归方法的基本思想。这是评论的根容器。
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;
Run Code Online (Sandbox Code Playgroud)
以下是您的 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;
Run Code Online (Sandbox Code Playgroud)
以下是您的评论组件。因为它是递归的,所以它将包含 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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
763 次 |
| 最近记录: |